lundi 31 août 2015

Find all numbers in a integer list that add up to a number

I was asked this question on an interview. Given the following list:

[1,2,5,7,3,10,13]

Find the numbers that add up to 5.

My solution was the following:

#sort the list:
l.sort()
result = ()
for i in range(len(l)):
    for j in range(i, len(l)):
         if l[i] + l[j] > 5:
             break
         elif l[i] + l[j] == 5:
             result += (l[i], l[j])

The idea I presented was to sort the list, then loop and see if the sum is greater than 5. If so, then I can stop the loop. I got the sense the interviewer was dissatisfied with this answer. Can someone suggest a better one for my future reference?



via Chebli Mohamed

Woocommerce Show default variation price

I'm using Woocommerce and product variations and all my variations have a default variation defined. I would like to know, how I can find the default variation and display it's price.

This is the code I got so far, but it displays the cheapest variation price, and I'm looking for my default variation product price instead.

// Use WC 2.0 variable price format, now include sale price strikeout
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
    $price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
}
return $price;

}

I found the code example here Woocommerce variation product price to show default



via Chebli Mohamed

Powershell parsing regex in text file

I have a text file:

Text.txt

2015-08-31 05:55:54,881 INFO   (ClientThread.java:173) - Login successful for user = Test, client = 123.456.789.100:12345
2015-08-31 05:56:51,354 INFO   (ClientThread.java:325) - Closing connection 123.456.789.100:12345

I would like output to be:

2015-08-31 05:55:54 Login user = Test, client = 123.456.789.100
2015-08-31 05:56:51 Closing connection 123.456.789.100

Code:

$files = Get-Content "Text.txt"
$grep = $files | Select-String "serviceClient:" , "Unregistered" |  
Where {$_ -match '^(\S+)+\s+([^,]+).*?-\s+(\w+).*?(\S+)$' } |
Foreach {"$($matches[1..4])"} | Write-Host

How can I do it with the current code?



via Chebli Mohamed

How to preprocess high cardinality categorical features?

I have a data file which has features of different mobile devices. One column with categorical data type has 1421 distinct types of values. I am trying to train a logistic regression model along with other data that I have. My question is: Will the high cardinality column described above affect the model I am training? If yes, how do I go about preprocessing this column so that it has lower number of distinct values?



via Chebli Mohamed

Meteor cursor counts and forEach

I need to add min and max fields into collection items in publish function and filter items by this fileds. I found the solution by using forEach for cursor:

Meteor.publish 'productsWithMinMax', (filter, options) ->
    Products.find(filter, options).forEach (p) =>
        p.min = Math.min p.price1, p.price2, p.price3, p.price4
        p.max = Math.max p.price1, p.price2, p.price3, p.price4

        if p.min && p.max && (p.max < p.mainPrice || p.min > p.mainPrice )
            @added "products", p._id, p

    Counts.publish @, 'numberOfProductsWithMinMax', Products.find(filter), {noReady: true}

    @ready()

But now Counts.publish returns wrong count for my cursor. How to count my cursor in this case?



via Chebli Mohamed

ES6 Import Folder

Does the ES6 module syntax allow you to import something from a folder?

For example if I have ./sub/main.js and I try import foo from './sub in the ./main.js file, will this work?

Could I get this sort of importing from a folder to work with babel and webpack?

Basically this would be the equivalent of __init__.py in Python.



via Chebli Mohamed

Is there a custom of distributing a key description with databases, like it is done with maps?

For a project with a more complicated relational database structure, one of the requirements is long-term stability of the SQL database. To achieve this, I did some searching for a standard way of describing certain paths through a relational database. For example, this would include a description on how to combine related tables or a hierarchy of the keys/IDs used in the database.

What I am trying to do is a description of the database, so that someone who just imports the database dump to a SQL server will know how what queries to write and what fields to use as keys. (This situation could arise if, for example, the software used with the database can no longer be run at some point in time.)

While I am aware this could be done with UML, I'd like to ask whether there is some sort of standard or custom of distributing databases in open source software with a description, like the key always printed on maps so that people know what each color and line type means. Thanks!



via Chebli Mohamed

Download Google Sheet as CSV and keep numbers values as text

When I download one of my Google Sheets to csv, it removes the proceeding "0" from my values. For example, "0666666" will become "666666". How can I modify the code below so that it keeps that front zeros? Thanks!

def static_tabs():
    static_tabs = ('Locating Media','Schedules')
    for tab in static_tabs:
        edit_ws = edit.worksheet(tab)
        print ("EDIT"+format(edit_ws))
        filename = str(tab) +'.csv' 
        with open('C:/Users/A_DO/Dropbox/2. The Machine/10. Edit and QC Google Doc/Edit/Static Tabs/' + filename, 'wb') as f:
            writer = csv.writer(f,quoting=csv.QUOTE_ALL)
            writer.writerows(edit_ws.get_all_values())

static_tabs()



via Chebli Mohamed

NpmInstallDir parameter not found with MSBuild of Apache Cordova project

I'm using VS2015 to build an Apache Cordova project. This builds fine using the editor itself, however when I run the build using MSBuild:

"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" /p:Configuration=Release MySolution.sln"

I encounter the following error:

(InstallMDA target) -> C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(287,5): error MSB4044: The "RunMdaInstall" task was not given a value for the required parameter "NpmInstallDir".

Opening the Microsoft.MDA.FileMirrorring.targets file, I see the reference to NpmInstallDir. How is this supposed to get set during an MSBuild? (Needless to say, running echo %NpmInstallDir% on my commandline does not return a path, so I don't have this set.)

Doing a search for NpmInstallDir in the directory where my Visual Studio lives, I see that it is retrieved through some arguments. Do I need to pass in a specific argument to MSBuild to locate NpmInstallDir?



via Chebli Mohamed

Pythpn Regex Select Element

I've got an array with elements which are different names such as and

[abc, def, agh § dsd, sdse, 12a § asd].

I would like to select only those that have § in it and erase the other elements from the array.

The names change in length and also the position of § in the name changes]

Does anybody have an idea?

Mine was

    names = [re.findall(r'(?<=>)[^><]+(?=<)', str(i).strip()) for i in select('§')]

However, my regex skills are below zero...so...help is much appreciated!



via Chebli Mohamed

How to set PHPStorm get existed word to autocomplete?

In Sublime Text, when I have helloWorldTesteStringLong written in an open file, it will show in auto complete list, independence if I in their file or not

How to can I set this configuration in PHPStorm? For show written word in autocomplete list



via Chebli Mohamed

Finding and replacing strings with certain character patterns in array

I have a pretty large database with some data listed in this format, mixed up with another bunch of words in the keywords column.

BA 093, RJ 342, ES 324, etc.

The characters themselves always vary but the structure remains the same. I would like to change all of the strings that obey this character structure : 2 characters A-Z, space, 3 characters 0-9 to the following:

BA-093, RJ-342, ES-324, etc.

Be mindful that these strings are mixed up with a bunch of other strings, so I need to isolate them before replacing the empty space.

I have written the beginning of the script that picks up all the data and shows it on the browser to find a solution, but I'm unsure on what to do with my if statement to isolate the strings and replace them.

<?php

require 'includes/connect.php';

$pullkeywords = $db->query("SELECT keywords FROM main");

while ($result = $pullkeywords->fetch_object()) {

    $separatekeywords = explode(" ", $result->keywords);
    print_r ($separatekeywords);
    echo "<br />";
}

Any help is appreciated. Thank you in advance.



via Chebli Mohamed

maven builds fails inside ubuntu vagrant machine as well as docker instance

I am developing an api using jaxb. The maven build (using jdk-7) works on my local windows machine. Now if I try to build it on my vagrant box (ubuntu/trusty64) after setting up maven and openjdk7 on the vm, I get following error on performing mvn clean install:

java.io.FileNotFoundException (operation not permitted)

However, if it is a simple java app, I am able to do perform maven builds on the same machine without error (from http://ift.tt/1COWknQ)

Detailed error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.4:war (default-war) on project '<app>' : Could not copy webapp classes [/usr/src/<app>/target/classes]: /usr/src/<app>/target/<app>-03.00.00.01-SNAPSHOT/WEB-INF/classes/<my-app-src>/rest/config/ResourceConfig.class (Operation not permitted) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.4:war (default-war) on project <my-app>: Could not copy webapp classes [/vagrant_data/<my-app-src>/<my-app>/target/classes]
[/vagrant_data/<my-app-src>/<my-app>/target/classes]
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:622)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Could not copy webapp classes [/vagrant_data/<my-apps-src>/target/classes]
    at org.apache.maven.plugin.war.packaging.ClassesPackagingTask.performPackaging(ClassesPackagingTask.java:80)
    at org.apache.maven.plugin.war.packaging.WarProjectPackagingTask.handleClassesDirectory(WarProjectPackagingTask.java:207)
    at org.apache.maven.plugin.war.packaging.WarProjectPackagingTask.performPackaging(WarProjectPackagingTask.java:104)
    at org.apache.maven.plugin.war.AbstractWarMojo.buildWebapp(AbstractWarMojo.java:505)
    at org.apache.maven.plugin.war.AbstractWarMojo.buildExplodedWebapp(AbstractWarMojo.java:433)
    at org.apache.maven.plugin.war.WarMojo.performPackaging(WarMojo.java:213)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:175)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.io.FileNotFoundException: /vagrant_data/<my-apps-src>/target/<my-app>-03.00.00.01-SNAPSHOT/WEB-INF/classes/<my-app-src>/rest/config/ResourceConfig.class (Operation not permitted)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:160)
    at org.codehaus.plexus.util.FileUtils.doCopyFile(FileUtils.java:1068)
    at org.codehaus.plexus.util.FileUtils.copyFile(FileUtils.java:1049)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFile(AbstractWarPackagingTask.java:334)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask$1.registered(AbstractWarPackagingTask.java:154)
    at org.apache.maven.plugin.war.util.WebappStructure.registerFile(WebappStructure.java:207)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFile(AbstractWarPackagingTask.java:149)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFiles(AbstractWarPackagingTask.java:104)
    at org.apache.maven.plugin.war.packaging.ClassesPackagingTask.performPackaging(ClassesPackagingTask.java:75)
    ... 27 more



via Chebli Mohamed

Controlling web application user access to file system

First, a preface: I'm new to Stack Overflow, recently reintroduced to programming, and very new to security, so please go easy on me. I'm hoping someone can point me in the right direction.

We are a large multi-site nonprofit organization with a small programming team supporting an obsolete Administration/Accounting software that was programmed in-house. In the last few years, part of our Human Resources module has been rewritten as an ASP.NET MVC web application (C#, Javascript, HTML) so that remote sites can install it and access employee information. The eventual plan is to move it all to RESTful Web Api, so I'm spending time on Pluralsight learning REST as well as the programming languages referenced above.

Where we've hit a snag is in security. Right now an authorized user in this web application has carte blanche access to data, so we can't make certain sensitive data available until we can employ authorization on a more granular level.

Our most pressing issue is document management. Documents on our old system are saved in a series of folders in .doc or .pdf format. Our web application needs to be able to authenticate a given user, access that same file structure and limit his/her access to only the folders he/she is authorized to view.

I've been searching stackoverflow and the internet, but haven't come across any clearcut information on how to proceed.

I would appreciate any input on strategies you may have used to tackle a similar problem. Thanks in advance for your help!



via Chebli Mohamed

How to dynamically traverse a global array without creating any copy of it?

For example something like this:

function POSTTraverse($key0 [, $key1 [, $key2 ...]]) {
    ...
    return $value;
}

The usage would be for example:

POSTTraverse('document', 'item', 'quantity', 5);



via Chebli Mohamed

XAML Binding: Combobox populating textbox in one scenario, but not another? WPF

I have one set of code working properly. It loads the "address" field from a database of user records containing stuff like [ID, Fname, Lname, address, zip, etc] into a ComboBox's selection set. Once a user selects an address it displays that selection in a corresponding textbox as well.

working code:

<Window x:Class="CC_Ticketing_WPF.MainWindow"
       xmlns:local="clr-namespace:CC_Ticketing_WPF"
       Title="MainWindow">
    <Window.Resources>
        <DataTemplate x:Key="orderheaderTemplate">
            <StackPanel>
                <TextBlock Text="{Binding XPath=address}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="cb_Address" 
                  DataContext="{StaticResource orderheaderDataSource}" 
                  ItemsSource="{Binding XPath=/dataroot/orderheader/address}"  
                  IsEditable="True"/>
        <TextBlock x:Name="tb_Address" 
                   Text="{Binding ElementName=cb_Address,Path=Text}"/>
    </StackPanel>
</Window>

The problem is I know that's very limited as it relies on defining everything in the stack panel. I am trying this something along these lines instead:

broken code

<Window x:Class="CC_Ticketing_WPF.MainWindow"
        xmlns:local="clr-namespace:CC_Ticketing_WPF"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow">
    <Window.Resources>
        <DataTemplate x:Key="orderheaderTemplate">
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="cb_Address" 
                  DataContext="{StaticResource orderheaderDataSource}" 
                  ItemsSource="{Binding XPath=/dataroot/orderheader}" 
                  DisplayMemberPath="address" 
                  SelectedValuePath="Content" 
                  IsEditable="True"/>
        <TextBlock x:Name="tb_Address" 
                   Text="{Binding ElementName=cb_Address,
                                  Path=SelectedItem.Content,
                                  Mode=OneWay}"/>
    </StackPanel>
</Window>

This loads the addresses and allows selection in the combobox, but sends nothing to the textbox. Eventually I'd want selecting an address from this combox to not only send the selection to the textbox, but also send the other relevant data from that record to other textbox's (like you select just an address and it populates a bunch of textboxes with the address, name, zip, etc.) Pretty common business need. Could someone put me on the right track here to accomplish this?



via Chebli Mohamed

Animate a div sliding with a toggle button

I can't seem to figure out how to animate my div sliding with a toggle button.

I tried using variables but I have multiple of these and I am creating too many variables to keep track of the clicks on each of them.

$(document).ready(function() {
  
  $('#toggle-sidebar').click(function() {
    $('#sidebar').animate({
      left: '200'
    }, 500);
  });
  
});
#sidebar {
  position: absolute;
  top: 0;
  left: 0;
  width: 20em;
  height: 70vh;
  background:#333;
}

#toggle-sidebar {
  float: right;
}
<script src="http://ift.tt/1oMJErh"></script>

<div id="sidebar"></div>

<a href="#" id="toggle-sidebar">Toggle</a>


via Chebli Mohamed

SQL update with sub-query takes too long to run

I have a SQL update query that runs with my test data, but doesn't complete (2 hours or more) with my production data.

The purpose of the query

I have an ADDRESSES table that uses code strings instead of IDs. So for example ADDRESSES.COUNTRY_CODE = "USA" instead of 3152. For referential integrity, I am changing these code strings to code IDs.

Schema

ADDRESSES

  • ADDR_ID (PK)
  • COUNTRY_CODE (varchar)
  • Address line 1 (varchar)
  • etc.

COUNTRY_CODES

  • CODE_ID (PK)
  • CODE_STRING (varchar)
  • etc.

Steps

First, I create a temporary table to store the address records with the appropriate code ID:

CREATE TABLE ADDRESS_TEMP
AS
   SELECT ADDR_ID, CODE_ID
     FROM    ADDRESSES
          LEFT JOIN
             COUNTRY_CODES
          ON ADDRESSES.COUNTRY_CODE = CODE_STRING

Second, I null the COUNTRY_CODE column and change its type to NUMBER.

Third I set the COUNTRY_CODE column to the code IDs:

UPDATE ADDRESSES
   SET COUNTRY_CODE =
          (SELECT ADDRESS_TEMP.CODE_ID
             FROM ADDRESS_TEMP
            WHERE ADDRESS_TEMP.ADDR_ID = ADDRESSES.ADDR_ID)

It is this third step that is taking hours to complete (2 hours and counting). The ADDRESSES table has ~356,000 records. There is no error; it is still running.

Question

Why isn't this update query completing? Is it dramatically inefficient? I think I can see how the sub-query might be an N2 algorithm, but I'm inexperienced with SQL.



via Chebli Mohamed

swap image and toggle div onclick

I have a dynamically populated unordered list. Every other list item is hidden. First list item contains an image, when clicked displays the list item immediately following. That part of my code is working fine. What I can't seem to figure out is how to swap the toggle image onclick. Right now the image stays the same

thank you for any help you can provide

$(document).ready(function () {
  $(".slidingDiv").hide();

  $('.show_hide').click(function (e) {
    $(".slidingDiv").slideToggle("slow");
    var val = $(this).src() == "http://ift.tt/1FdgyXH" ? "http://ift.tt/1MYsyCI" : "http://ift.tt/1FdgyXH";
    $(this).hide().src(val).fadeIn("slow");
    e.preventDefault();
  });
});
<script src="http://ift.tt/1qRgvOJ"></script>
<ul id="storeTable">
  <li id="one" class="alwaysVisable">
    <h3>Title</h3>
    <p class="descript">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <img src="http://ift.tt/1MYsyCI" class="show_hide" width="32" height="32">
  </li>
  <li class="slidingDiv">
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.
  </li>
  <li id="two" class="alwaysVisable">
    <h3>Title</h3>
    <p class="descript">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <img src="http://ift.tt/1MYsyCI" class="show_hide" width="32" height="32">
  </li>
  <li class="slidingDiv">
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.
  </li>
</ul>


via Chebli Mohamed

How to go back to an already launched activity in android

I want to go back to an already launched activity without recreating again.

  @Override
    public void onBackPressed() {
     Intent i = new Intent(SecondActivity.this, FirstActivity.class);
     this.startActivity(i);

    }

Instead of doing is there any other way to go back to another activity which is already created, which I get back with " Back button "



via Chebli Mohamed

how to shorten source code using whenall in order to optimize speed

I have used following code and its supposed to be used for calling more than 100,000 urls .

As its taking long time to finish the process , I am trying to find a better way to optimize the code.

I have read other questions like mine and few people suggested to remove toarray but there were example of how to do it.

Any comments would be appreciated.

private async Task ProcessAllURLSAsync(List<string> urlList)
{
    IEnumerable<Task> CallingTasksQuery =
        from url in urlList select ProcessURLAsync(url);

    Task[] CallingTasks = CallingTasksQuery.ToArray();

    await Task.WhenAll(CallingTasks);
}

private async Task ProcessURLAsync(string url)
{
    await CallURLAsync(url);
}

private async Task CallURLAsync(string url)
{
    var content = new MemoryStream();
    var webReq = (HttpWebRequest)WebRequest.Create(url);
    using (WebResponse response = await webReq.GetResponseAsync())
    {
    }
}



via Chebli Mohamed

How to map a Perforce depot's folder to an arbitrary local folder?

I have the following structure on the Perforce server:

MyDepot
  + MyProject
    + MySubProject
      + trunk
        + ... trunk folders/files ...

I have my Eclipse workspace for MySubProject in:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject

If I get the latest revision with a Perforce workspace of:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject

I get:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject\
  + MyDepot
    + MyProject
      + MySubProject
        + trunk
          + ... trunk folders/files ...

I'd prefer:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject\
  + ... trunk folders/files ...

Can I achieve this and if, how?

I found the P4V manual page Defining a Workspace View but it doesn't seem to cover what I want. (There's a garbled sentence under point 2. but this isn't essential in this respect, is it?)



via Chebli Mohamed

Tokenizing a string in Prolog using DCG

Let's say I want to tokenize a string of words (symbols) and numbers separated by whitespaces. For example, the expected result of tokenizing "aa 11" would be [tkSym("aa"), tkNum(11)].

My first attempt was the code below:

whitespace --> [Ws], { code_type(Ws, space) }, whitespace.
whitespace --> [].

letter(Let)     --> [Let], { code_type(Let, alpha) }.
symbol([Sym|T]) --> letter(Sym), symbol(T).
symbol([Sym])   --> letter(Sym).

digit(Dg)        --> [Dg], { code_type(Dg, digit) }.
digits([Dg|Dgs]) --> digit(Dg), digits(Dgs).
digits([Dg])     --> digit(Dg).

token(tkSym(Token)) --> symbol(Token). 
token(tkNum(Token)) --> digits(Digits), { number_chars(Token, Digits) }.

tokenize([Token|Tokens]) --> whitespace, token(Token), tokenize(Tokens).
tokenize([]) --> whitespace, [].  

Calling tokenize on "aa bb" leaves me with several possible responses:

 ?- tokenize(X, "aa bb", []).
 X = [tkSym([97|97]), tkSym([98|98])] ;
 X = [tkSym([97|97]), tkSym(98), tkSym(98)] ;
 X = [tkSym(97), tkSym(97), tkSym([98|98])] ;
 X = [tkSym(97), tkSym(97), tkSym(98), tkSym(98)] ;
 false.

In this case, however, it seems appropriate to expect only one correct answer. Here's another, more deterministic approach:

whitespace --> [Space], { char_type(Space, space) }, whitespace.
whitespace --> [].

symbol([Sym|T]) --> letter(Sym), !, symbol(T).
symbol([])      --> [].
letter(Let)     --> [Let], { code_type(Let, alpha) }.

% similarly for numbers

token(tkSym(Token)) --> symbol(Token).

tokenize([Token|Tokens]) --> whitespace, token(Token), !, tokenize(Tokens).
tokenize([]) --> whiteSpace, [].

But there is a problem: although the single answer to token called on "aa" is now a nice list, the tokenize predicate ends up in an infinite recursion:

 ?- token(X, "aa", []).
 X = tkSym([97, 97]).

 ?- tokenize(X, "aa", []).
 ERROR: Out of global stack

What am I missing? How is the problem usually solved in Prolog?



via Chebli Mohamed

Git issues with shared folders in Vagrant

I have never seen this issue before while using Vagrant, so I'm hoping this makes sense to someone. I have a folder that contains a git repository, that is being synced with a Vagrant machine running CentOS 6.5, and seeing some inconsistencies with Git.

On my host machine (Mac OSX) if I run git status I get the following:

 ~/Folder/repo$ git status
 On branch master
 Your branch is up-to-date with 'origin/master'.
 nothing to commit, working directory clean

But if I run the same command within my vagrant box, I get the following:

vagrant@localhost ~/repo$ git status                                                                                                                 master
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   .codeclimate.yml
#   modified:   .gitattributes
#   modified:   .gitignore
#   modified:   CONTRIBUTING.md
#   modified:   app/commands/.gitkeep
#   modified:   app/commands/CreateModule.php
#   modified:   app/commands/FbAdRevenue.php
....

And the list goes on, basically git locally seems to think that every single file has been modified and not committed which is not true. Any idea why this would be the case and how to fix it?



via Chebli Mohamed

Sparql insert data not working

I'm a newbie to Sparql, but I am unable even to make a simple insert data query, or so it seems.

I'm using Apache Fuseki as working server; I'm in a graph, and I'm trying to make this query work:

PREFIX oa: <http://ift.tt/1FdgyHl;
PREFIX rdfs: <http://ift.tt/1cmhdKn;

INSERT DATA{             
  [ a 
    oa:Annotation ;                    
    rdfs:label "Title";                    
  ] .                    
}

But it doesn't matter what I do, I keep getting this error:

Error 400: SPARQL Query: No 'query=' parameter

This is even a semplified code, I tried many queries even more complex, but the result doesn't change...



via Chebli Mohamed

Ionic Changes Content-Type

Ok I have to make a simple GET request that work in Postman but not in the Ionic code. I have determined that the reason is that the API treats incoming requests differently based on Content-Type. application/json works text doesn't.

    headers: {
      "Content-Type": 'application/json; charset=UTF-8',
      "Accept": 'application/json; charset=UTF-8'
    },

As you can see I'm setting the header to try to force application/json but when I sniff the request it has changed to text/html somehow. How do I force Ionic to take my Content-Type as definitive?



via Chebli Mohamed

user authentication methods for apple watch app

I have an iPad and iPhone application,which runs on user session and requires login and session to be maintained throughout application life cycle. Now I want to create Apple watch app for same app. What are the best ways to do login and maintain session on Apple watch. User session expires if app is idle for more than 20 minutes.



via Chebli Mohamed

Using FileReader.readAsArrayBuffer() on changed files in Firefox

I'm running into an odd problem using FileReader.readAsArrayBuffer that only seems to affect Firefox (I tested in the current version - v40). I can't tell if I'm just doing something wrong or if this is a Firefox bug.

I have some JavaScript that uses readAsArrayBuffer to read a file specified in an <input> field. Under normal circumstances, everything works correctly. However, if the user modifies the file after selecting it in the <input> field, readAsArrayBuffer can get very confused.

The ArrayBuffer I get back from readAsArrayBuffer always has the length that the file was originally. If the user changes the file to make it larger, I don't get any of the bytes after the original size. If the user changes the file to make it smaller, the buffer is still the same size and the 'excess' in the buffer is filled with character codes 90 (capital letter 'Z' if viewed as a string).

Since this code is so simple and works perfectly in every other browser I tested, I'm thinking it's a Firefox issue. I've reported it as a bug to Firefox but I want to make sure this isn't just something obvious I'm doing wrong.

The behavior can be reproduced by the following code snippet. All you have to do is:

  1. Browse for a text file that has 10 characters in it (10 is not a magic number - I'm just using it as an example)
  2. Observe that the result is an array of 10 items representing the character codes of each item
  3. While this is still running, delete 5 characters from the file and save
  4. Observe that the result is still an array of 10 items - the first 5 are correct but the last 5 are all 90 (capital letter Z)
  5. Now added 10 characters (so the file is now 15 characters long)
  6. Observe that the result is still an array of 10 items - the last 5 are not returned
function ReadFile() {
  var input = document.getElementsByTagName("input")[0];
  var output = document.getElementsByTagName("textarea")[0];

  if (input.files.length === 0) {
    output.value = 'No file selected';
    window.setTimeout(ReadFile, 1000);
    return;
  }

  var fr = new FileReader();
  fr.onload = function() {
    var data = fr.result;
    var array = new Int8Array(data);
    output.value = JSON.stringify(array, null, '  ');
    window.setTimeout(ReadFile, 1000);
  };
  fr.readAsArrayBuffer(input.files[0]);

  //These two methods work correctly
  //fr.readAsText(input.files[0]);
  //fr.readAsBinaryString(input.files[0]);
}

ReadFile();
<input type="file" />
<br/>
<textarea cols="80" rows="10"></textarea>

In case the snippet does not work, the sample code is also available as a JSFiddle here: http://ift.tt/1MYsymg



via Chebli Mohamed

intellij internal webserver using htaccess

IntelliJ 14 has a built-in Webserver where you can run html-files on localhost port 63342. Is there any possibility to use rewrite rules (like modrewrite) within a .htaccess file or something similar?

Or do I have to install a local webserver for this?

Regards, Jens



via Chebli Mohamed

When using a RegEx in AutoFixture ISpecimenBuilder, Why do I always get back the same value?

My builder is set up to either deal with a Parameter or a Property. This may change in the future, but for now this is what I have in my builder:

public class UserNameBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
       var propertyInfo = request as PropertyInfo;
        if (propertyInfo != null && propertyInfo.Name == "UserName" && propertyInfo.PropertyType == typeof(string))
        {
            return GetUserName();
        }

        var parameterInfo = request as ParameterInfo;
        if (parameterInfo != null && parameterInfo.Name == "userName" && parameterInfo.ParameterType == typeof(string))
        {
            return GetUserName();
        }

        return new NoSpecimen(request);
    }

    static object GetUserName()
    {
        var fixture = new Fixture();
        return new SpecimenContext(fixture).Resolve(new RegularExpressionRequest(@"^[a-zA-Z0-9_.]{6,30}$"));
    }
}

My UserName object is a ValueType object and is as follows:

public class UserName : SemanticType<string>
{
    private static readonly Regex ValidPattern = new Regex(@"^[a-zA-Z0-9_.]{6,30}$");

    public UserName(string userName) : base(IsValid, userName)
    {
        Guard.NotNull(() => userName, userName);
        Guard.IsValid(() => userName, userName, IsValid, "Invalid username");
    }

    public static bool IsValid(string candidate)
    {
        return ValidPattern.IsMatch(candidate);
    }

    public static bool TryParse(string candidate, out UserName userName)
    {
        userName = null;

        try
        {
            userName = new UserName(candidate);
            return true;
        }
        catch (ArgumentException ex)
        {
            return false;
        }
    }
}

The UserName class inherits from SemanticType which is a project that provides a base for my value types.

Whenever I use AutoFixture as follows:

var fixture = new Fixture();
fixture.Customizations.Add(new UserNameBuilder());

var userName = fixture.Create<UserName>();

I always get the value "......" I thought I would get a different value each time. Is what I'm seeing expected behavior?

Thanks



via Chebli Mohamed

swift remoteControlReceivedWithEvent giving fatal error: unexpectedly found nil while unwrapping an Optional value

I am using below function to play/pause the music and I am implementing remote controls:

in ViewController.swift :

static let sharedInstance = ViewController()
@IBOutlet var PausePlay: UIButton!


var BackgroundAudio = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ants", ofType: "mp3")!), error: nil)

//in info.playlist I have added 'Required background modes and add to idem 0 ap plays audio airplay then below code to play even when iphone is locked: -marcin

    PausePlay.setTitle("Play", forState: UIControlState.Normal)

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)

    // Do any additional setup after loading the view, typically from a nib.
    PausePlay.setTitle("Play", forState: UIControlState.Normal)
    if NSClassFromString("MPNowPlayingInfoCenter") != nil {
        let image:UIImage = UIImage(named: "logo_player_background")!
        let albumArt = MPMediaItemArtwork(image: image)
        var songInfo: NSMutableDictionary = [
            MPMediaItemPropertyTitle: "Ants",
            MPMediaItemPropertyArtist: "The App",
            MPMediaItemPropertyArtwork: albumArt
        ]
        MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo as [NSObject : AnyObject]
    }
    if (AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)) {
        println("Receiving remote control events")
        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    } else {
        println("Audio Session error.")
    }

in AppDelegate.swift I have this for remote control:

override func remoteControlReceivedWithEvent(event: UIEvent) {
        if event.type == UIEventType.RemoteControl {
        if event.subtype == UIEventSubtype.RemoteControlPlay {
            println("received remote play")
            ViewController.sharedInstance.FuncPausePlay() // these are producing terrible error
        } else if event.subtype == UIEventSubtype.RemoteControlPause {
            println("received remote pause")
            ViewController.sharedInstance.FuncPausePlay() // these are producing terrible error
        } else if event.subtype == UIEventSubtype.RemoteControlTogglePlayPause {
            println("received toggle")
            ViewController.sharedInstance.BackgroundAudio.stop()
        }
    }
}

when I am hitting play button then app works file on my phone (it plays the sound) but I am getting below info in Xcode error window:

Receiving remote control events 2015-08-31 19:33:42.735 The App[1501:292732] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "", "", "" ) Will attempt to recover by breaking constraint Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.

then when I lock my phone, sound is still playing (which if great) but when I am hitting pause button on remote control screen (when my phone is locked) then app is freezing / stopping and I get below info in Xcode :

received remote pause fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

What am I doing wrong? Please help.



via Chebli Mohamed

How can I visualize a data.frame with a values column and a label column in R?

I'm using the pdf command and ggplot2 to create couple different types of graphs and while I'm at it I'd like to throw in some simple tables (with, for example, column labels being coefficient names and rows having values) but I'm not sure to make a "plot" out of that without going separately into excel to make a table (but then I don't know how to insert it into the pdf I generate with R)

For example suppose I've got a data.frame like this one:

set.seed(1)
foo = data.frame(val1=rnorm(5), val2=rnorm(5), columnLabels=c('A','B','C','D','F'))

Is there a simple way to "plot" a simple table with those column labels, with row labels like c('Val 1', 'Val2') and with the corresponding values?



via Chebli Mohamed

Email Attachment From Lotusscript Agent

I have documents that get processed via a scheduled LotusScript agent. Each document has a $FILE field which is a jpg photo. In my agent, I want to take that photo on the document and email it to a specified address. Is this possible with a scheduled LotusScript agent?



via Chebli Mohamed

NetLogo: how to make the calculation of turtle movement easier?

I am working with NetLogo code written with somebody else (freely available to public). I try to understand how the procedure of turtle moving is elaborated and, most important - how make it computationally faster without loosing sensitivity of turtle movement in relation to worlds' patches?

I suppose that the most of the calculation time is used to calculate the distance of each step of turtle movement - I would like to measure only one variable from patch of turtle's origins to last patch where it will stay. I have decoded some of features but I am still not able to reproduce them. I'll really appreciate any help !

My understanding what the procedure could accomplish:

enter image description here

to move-turtles                                                                    
   ifelse perceptdist = 0                                                           
    [ifelse patch-ahead 1 != nobody 
     [rt random moveangle lt random moveangle                                      
      let xcorhere [pxcor] of patch-here                                           
      let ycorhere [pycor] of patch-here                                           
      fd 1
      let xcornext [pxcor] of patch-here                                           
      let ycornext [pycor] of patch-here                                           
      set dist sqrt (xcor * xcor + ycor * ycor)                                        
      set t_dispers (t_dispers + 1)                                                 
      set energy (energy - (1 / efficiency))                                       
      let flightdistnow sqrt ((xcornext  - xcorhere) * (xcornext  - xcorhere) + (ycornext - ycorhere) * (ycornext - ycorhere))   
      set flightdist (flightdist + flightdistnow)

    ][]]     

   [let np patches in-radius perceptdist          ; find the patch with the highest totalattract value within perception range                                 
    let bnp max-one-of np [totalattract]                                              
    let ah [totalattract] of patch-here
    let xcorhere [pxcor] of patch-here
    let ycorhere [pycor] of patch-here                                             
    let abnp [totalattract] of bnp                                                 
    ifelse abnp - ah > 2 and random-float 1 < 0.1                                  
     [move-to bnp                                     ; move to the patch with the highest attractivity value
      let xbnp [pxcor] of bnp                                 
      let ybnp [pycor] of bnp
      let flightdistnow sqrt ((xbnp - xcorhere) * (xbnp - xcorhere) + (ybnp - ycorhere) * (ybnp - ycorhere)) 
      set t_dispers (t_dispers + flightdistnow)                
      set energy (energy - (flightdistnow / efficiency))      ; how the turtle decision to stay/move further is made - ratio of turtle energy/efficiency  
      set flightdist (flightdist + flightdistnow)
      set dist sqrt (xcor * xcor + ycor * ycor)               

   [rt random moveangle lt random moveangle                                        
    set dist sqrt (xcor * xcor + ycor * ycor)                                      
    set t_dispers (t_dispers + 1)                                                  
    set energy (energy - (1 / efficiency))                                         
    let xcorhere2 [pxcor] of patch-here                                           
    let ycorhere2 [pycor] of patch-here                                            
    fd 1
    let xcornext2 [pxcor] of patch-here                                            
    let ycornext2[pycor] of patch-here                                             
    set dist sqrt (xcor * xcor + ycor * ycor)                                         
    let flightdistnow sqrt ((xcornext2  - xcorhere2) * (xcornext2  - xcorhere2) + (ycornext2 - ycorhere2) * (ycornext2 - ycorhere2))   
    set flightdist (flightdist + flightdistnow)

end  



via Chebli Mohamed

How to prevent loading the same data over and over in angularJS

I have an object that contains some data that I need to load when my application starts. Once its loaded I need to be able to reuse in multiple places on my application.

What is the best way to do this?

Right now I have a factory that I inject into my controller and I pull the data, the problem is that I'm doing the data pull multiple times.

What would be the best way to pull the data only when I load the application? I would only need to access the data on my templates and pull the correct Key Value from the object where I need.



via Chebli Mohamed

Indexed View in SQL Server

Can I create an index on a view which references synonyms which point to a linked server? Since the view isn't based on local tables I wasn't sure if it was possible.



via Chebli Mohamed

Is Telegram bot token secure: does SSL encrypt the requested URL?

Is Telegram bot token secure as long as it's being use in url for each api method call? Is there a risk that someone steal Telegram token in the way to Telegram servers ?

Or in other words: Does SSL encrypt the url itself ?



via Chebli Mohamed

please help !! . I can't Create any SharedPrefrences

I usually use this code for create sharedPrefs file :

SharedPrefrences SP = getSharedPrefrences("MYPREF",0);
SP.getString("Username","x");

But now if i see this directory :

"/data/data/packageName/" 

There is not any shared_prefs directory. Another thing : if I use Editor its work properly. Please help me ..



via Chebli Mohamed

a href not working with a bare web page

I've been looking around for a solution to the problem I'm having, but it seems that none of the solutions on SO address my issue.

I was having the dreaded issue where the a href tag in my HTML does not actually take me to the link. At first, I tried removing the JavaScript includes, wondering if something in the JavaScript portion was messing up the page.

Then I removed the CSS portion as well, and ultimately removed everything until the page consisted of simply the header information for the HTML page and only the a href tag. I also changed the link to a non-existent page (to force a 404 error).

When clicking on the link, it keeps me on the current page and doesn't take me to the referenced page (or even give me a 404 error). Following is the stripped out code (everything but the commented out portion):

 <html>
 <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no" />
    <title>test</title>

    <meta name="description" content="test1" />

    <meta name="keywords" content="test2" />
 </head>

  <a href="test.html">Support</a/>

 </html>

Thanks for the help.



via Chebli Mohamed

Sorting a list according to date [duplicate]

This question already has an answer here:

I have a struct and a list as follow, I just wanted to sort the Inputpoints according to date. I have used the following commands but I can not see any sorting.

public struct Points
{
    public Date Date;
    public double Quantity;
}
_test = new List<Points>(InputPoints);
_test.OrderBy(t => t.Date);

Thanks



via Chebli Mohamed

deserialize json to c# string

I apologize if I'm asking the same question again, but I have a simple JSON string that I need to deserialize. But I can use .NET 3.5 only. Here's my string:

{
  "DataCon": {
    "ActivityID": "ACT001",
    "RequestID": 123,
    "CRMID": 998989,
    "LeadID": "LEAD001",
    "ProcessName": "PROC",
    "ContatcID": "CON001"
  },
  "Errors": [

  ],
  "Warnings": [

  ]
}

Please help me find a solution using .NET 3.5 only



via Chebli Mohamed

Guess I'm Not Understanding how httpcontext.current.response.binarywrite works

Let me start by saying if I'm making this overly complicated, please, please offer suggestions on how to simplify!! I'm trying to create some logic that will let users export the contents on the screen to a PDF file. The contents contains multiple highcharts graphs, so I need for the html to be rendered completely to the page so I can grab the svg information to pass into the PDF file. Since the page has been rendered completely, the only way I know to pass the rendered html back to the server is through Web Services. Web Services is calling a .cs file where the PDF functionality is located. I can set a break point in the .cs file at the end of the pdf function, and it is hitting it. The problem is, it's returning an error of "200 OK parsererror SyntaxError: Unexpected token %".

Now, I create a dummy html string in my C# codebehind and call the .cs file from the codebehind, and it creates a PDF file with no issues at all. So my question is, why would the class work when being called from a codebehind, but not from Web Services? The only thing I can think of, is that it has something to do with a postback? My code is below:

JavaScript that is calling the Web Service..I can step all the way through the web service and class functions being called, they are making it to the end, but it's returning to the error function with 200 OK parsererror SyntaxError: Unexpected token %

function checkSplash() {
    timesChecked++;
    if (loadImages >= document.getElementsByName('img').length || timesChecked * checkInterval >= maxLoadTime) {
        clearInterval(intervalID);

        if (document.getElementById("exportDiv") != null) {
            var mydata = {
                src: document.getElementById("export_pdf").innerHTML
            }

            $.ajax({
                type: "post",
                contentType: "application/json; charset=UTF-8",
                url: "../WebServices/print.asmx/export",
                data: JSON.stringify(mydata),
                dataType: "json",
                success: function (response) {
                    alert("here");
                    location.reload(true);
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(xhr.status + ' ' + xhr.statusText + ' ' + textStatus + ' ' + errorThrown);
                }
            })
        }
    }
}

Web Service being called...this function is identical the a test function I created in the codebehind. The codebehind test function works and creates the PDF document with no issues. But when this gets called from the javascript, it returns the error

using DMC.Classes;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DMC.WebServices
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]

    public class print : System.Web.Services.WebService
    {
        [WebMethod]
        public bool export(string src)
        {
            string fileName = null;
            export dmc = new export();

            fileName = " Behavior Statistics YTD ";

            dmc.exportPDF(fileName, "Portrait", src);

            return true;
        }
    }
}

Finally, the .cs methods being used:

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using NReco.PdfGenerator;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace DMC.Classes
{
    public class export 
    {
        public void exportPDF(string fileName, string Orientation, string html)
        {
            HtmlToPdfConverter pdf = new HtmlToPdfConverter();

            html = html.Replace("\n", "");
            html = html.Replace("\t", "");
            html = html.Replace("\r", "");
            html = html.Replace("\"", "'");

            switch (Orientation)
            {
                case "Portrait":
                    pdf.Orientation = PageOrientation.Portrait;
                    break;
                case "Landscape":
                    pdf.Orientation = PageOrientation.Landscape;
                    break;
                default:
                    pdf.Orientation = PageOrientation.Default;
                    break;
            }

            pdf.Margins.Top = 25;
            pdf.PageFooterHtml = createPDFFooter();

            var pdfBytes = pdf.GeneratePdf(createPDFScript() + html + "</body></html>");

            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.ContentEncoding =  System.Text.Encoding.UTF8;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");
            HttpContext.Current.Response.BinaryWrite(pdfBytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        private string createPDFScript()
        {
            return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var x=document.location.search.substring(1).split('&');for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" +
        "var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var i in x) {var y = document.getElementsByClassName(x[i]);" +
        "for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];}}</script></head><body onload=\"subst()\">";
        }

        private string createPDFFooter()
        {
            return "<div><table style='font-family:Tahoma; font-size:9px; width:100%'><tr><td style='text-align:left'>Research Dept|RR:mm:jpg</td><td style='text-align:right'>Page <span class=\"page\"></span> of <span class=\"topage\"></span></td></div>";
        }
    }
}



via Chebli Mohamed

C# HLSL/XNA/MonoGame Problems

First of all, im new to shaders and xna.

I've been trying to follow this tutorial: http://ift.tt/1UbWeP2

I've done everything he said, I even ended up copy/pasting some parts to be totally sure although – it still won't work.

    sampler s0;
    texture lightMask;
    sampler lightSampler=sampler_state {
      Texture=<lightMask>;
    }
    ;
    float4 PixelShaderLight(float2 coords:TEXCOORD0):COLOR0 {
      float4 color=tex2D(s0, coords);
      float4 lightColor=tex2D(lightSampler, coords);
      return color * lightColor;
    }
    technique Technique1 {
      pass P0 {
        PixelShader=compile ps_4_0_level_9_1 PixelShaderLight();
      }
    }

The problem is that when I apply the pass 0 everything goes black.

My guess is that the lightcolor is returning zero. The lightmask is a renderTarget where I've painted my lights on.

I really dont know why lightcolor would return zero. If that is the case, could anyone give me a hint in what I'm doing wrong?

Here is my main class if you want to look at it:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace TestingGame
{
    public class TestingGame : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Location loc;

        public static Texture2D lightMask;
        public static Texture2D img;
        public static Effect effect1;
        RenderTarget2D lightsTarget;
        RenderTarget2D mainTarget;

        public TestingGame()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            loc = new Location(20,20);

            var pp = GraphicsDevice.PresentationParameters;
            lightsTarget = new RenderTarget2D(
            GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);
            mainTarget = new RenderTarget2D(
            GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);

            base.Initialize();
        }

        protected override void LoadContent()
        {

            spriteBatch = new SpriteBatch(GraphicsDevice);

            lightMask = Content.Load<Texture2D>("lightmask.png");
            img = Content.Load<Texture2D>("img.png");
            effect1 = Content.Load<Effect>("lighteffect");

        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            if(loc.Equals(new Location(21,20)))
                System.Console.WriteLine("Working");
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(lightsTarget);
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);

            spriteBatch.Draw(lightMask, new Vector2(20, 20), Color.Red);

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(mainTarget);
            GraphicsDevice.Clear(Color.Transparent);
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

            spriteBatch.Draw(img, new Vector2(50,50));

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

            effect1.Parameters["lightMask"].SetValue(lightsTarget);
            effect1.CurrentTechnique.Passes[0].Apply();
            spriteBatch.Draw(mainTarget, Vector2.Zero, Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}



via Chebli Mohamed

`using` declaration for a user-defined literal operator

Is it possible to have a using declaration for the literals operator, operator ""?

E.g.,

#include <chrono>

namespace MyNamespace
{
  constexpr std::chrono::hours operator "" _hr(unsigned long long n){
    return std::chrono::hours{n};
  }

  // ... other stuff in the namespace ...
}

using MyNamespace::operator"";    // DOES NOT COMPILE!

int main()
{
  auto foo = 37_hr;
}

My work-around has been to put these operators in their own nested namespace called literals, which allows using namespace MyNamespace::literals;, but this seems somewhat inelegant, and I don't see why the using directive can't be used for operator functions in the same way as it can for any other functions or types within a namespace.



via Chebli Mohamed

Size of PriorityQueue increases when a non-comparable object is added

Consider the following code:

import java.util.PriorityQueue;

public class Test {

    public static void main(String argv[]) {
        PriorityQueue<A> queue = new PriorityQueue<>();
        System.out.println("Size of queue is " + queue.size()); // prints 0
        try {
            queue.add(new A());
        } catch (ClassCastException ignored) { }
        System.out.println("Size of queue is " + queue.size()); // prints 1
    }

} 
class A { } // non-comparable object

In this code, an object, which is explicitly non-comparable, is added to a PriorityQueue. As expected per PriorityQueue.add Javadoc, this code throws a ClassCastException because the object is not comparable.

However, it seems that the size of the queue is still increased, although an exception was thrown.

I would have expected both print statements to output 0 but the second one actually outputs 1, as if an object had been added to the queue.

I find this really strange, is this behaviour expected? If so, what is the reason behind this and where is it documented? I can't find anything related to this.



via Chebli Mohamed

CSS @Keyframes - experts opinion wanted

this is my 'very first' foray into keyframe animation. I was put off before by the alleged inability to dynamically change hard coded CSS values on the fly via JavaScript.

I Googled around a bit to find it 'can' be done but with a lot of fiddly work finding, removing and replacing parts of or whole stylesheets.

Anyway, here's my effort. The eventual goal of this particular script is to be the bounce of clock hand. I can already do this with transition and cubic bezier but can only get one bounce in. I've seen this effect using various js libraries etc but you know how it is - you like to roll your own.

My question is - Is there anything glaringly wrong with my method below. Ignore the trivia, it's just a test. What I want looking at is my GenerateKeyFrames() function and the two methods of calling it.

Thanks for any info.

    var d = document;
    var incr = 1;
    var step = -6; //Initial start pos.

    var coreCss = 'display: block;position: absolute;'
               +'left: 100px;top: 10px;height: 95px;'
               +'width: 4px;background-color: #000;'
               +'transform-origin: center bottom;';

    var initialAniCss = 'animation: reGen'+incr+' 1s 1 forwards;';
    coreCss += initialAniCss;

    var elementToAnimate = d.createElement('div');
    elementToAnimate.setAttribute('style', coreCss);
    d.body.appendChild(elementToAnimate);

    function GenerateKeyFrames() {

    /* Remove previous 'tmpSheet' stylesheet */
    var currSheet = (d.getElementById('tmpSheet'));
    if (currSheet) {
        //currSheet.parentNode.removeChild(currSheet);// Doesn't seem as smooth as other 2 below!
        //currSheet.remove(); - Not IE, shame.
        currSheet.outerHTML = '';
    }

    /* Movement in degrees */
    var p1 = step;
    var p2 = step+6;
    var p3 = step+4;
    var p4 = step+6;
    var p5 = step+5; 
    var p6 = step+6;

    /* Create new keyframe. Must have new name! Adding an incrementing var to name does ok */
    var frames = '@keyframes reGen'+incr+' { '
    +'0% { transform: rotate('+p1+'deg) translateZ(0); animation-timing-function: ease-in;}'
    +'25% { transform: rotate('+p2+'deg) translateZ(0); animation-timing-function: ease-out;}'
    +'45% { transform: rotate('+p3+'deg) translateZ(0); animation-timing-function: ease-in;}'
    +'65% { transform: rotate('+p4+'deg) translateZ(0); animation-timing-function: ease-out;}' 
    +'75% { transform: rotate('+p5+'deg) translateZ(0); animation-timing-function: ease-in;}'
    +'85%,100% { transform: rotate('+p6+'deg) translateZ(0);animation-timing-function: ease-out;}}';

    /* Create new tmpSheet style sheet to head */
    var s = document.createElement( 'style' );
    s.setAttribute("id", "tmpSheet");
    s.innerHTML = frames;
    document.getElementsByTagName('head')[0].appendChild(s);

    /* Put it all together and it's ready to go */ 
    var newAni = 'animation: reGen'+incr+' 1s 1 forwards;';
    coreCss += newAni;
    elementToAnimate.setAttribute('style', coreCss);
    d.body.appendChild(elementToAnimate);
}
GenerateKeyFrames();

/* Can be called on animation end - or timed function rep().
elementToAnimate.addEventListener("animationend",function(e) {
    incr++;
    step += 6;
    elementToAnimate.removeAttribute("style");
    GenerateKeyFrames();
    },false);
*/

function rep() {
    incr++;
    step += 6;
    elementToAnimate.removeAttribute("style");
    GenerateKeyFrames();
setTimeout(rep, 2000);
}
rep();


via Chebli Mohamed

How to consume npm react-art module without bundling?

There is no CDN for React-art library. So, I installed it via npm install react-art in the local asp.net project.

In the cshtml file where I use the ReactART object, I used the following script:

  <script src="http://ift.tt/1KXYNNU"></script>
  <script src="http://ift.tt/1ERkbBe"></script>
  <script src="http://ift.tt/1jyb1yI"></script>
  <script src="http://ift.tt/1JmkwQq"></Script>
  <script src="http://ift.tt/1KXYPp8"></script>
  <script src="..\..\node_modules\react-art\lib\reactart.js"></script>

But I can't get the reference to the ReactART object.

How can I consume react-art and it's dependencies?



via Chebli Mohamed

Force wordcloud python module to include all words

I'm using the wordcloud module in Python by Andreas Mueller to visualize results of a survey my students will complete. Brilliant module, very nice pictures, however I have trouble making it recognize all words, even when setting stopwords=None and ranks_only=True. The survey responses are between one and three words long and may contain hyphens.

Here is an example. First I install dependencies in my Jupyter notebook:

import matplotlib.pyplot as plt
%matplotlib inline
from wordcloud import WordCloud
from scipy.misc import imread

Then suppose I put all the responses into a string:

words = "do do do do do do do do do do re re re re re mi mi fa fa fa fa fa fa fa fa fa fa-so fa-so fa-so fa-so fa-so so la ti do"

Then I execute the plot:

wordcloud = WordCloud(ranks_only = True,stopwords=None).generate(words)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

But for some reason it ignores "do" and "fa-so" despite their high frequency.

Any tips? Besides "don't use a word cloud". It is a silly survey and it invites a silly visualization. Thanks.

Update

Still unable to include hyphened words (e.g. "fa-so"), they just drop out.



via Chebli Mohamed

Differences between using a method reference and function object in stream operations?

When using Java 8 streams I often find that I need to refactor a multi-statement lambda expression. I will illustrate this with a simple example. Assume I have started writing this code:

Stream.of(1, 3).map(i -> {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
}).forEach(System.out::println);

Now I am not very fond of the large lambda expression in the map call. Hence, I want to refactor it out of there. I see two options, either I make an instance of Function in my class:

private static Function<Integer, String> mapper = i -> {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
};

and use it like this:

Stream.of(1, 3).map(mapper).forEach(System.out::println);

Or I simply make a method:

private static String map(Integer i) {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
}

and use a method reference:

Stream.of(1, 3).map(Test::map).forEach(System.out::println);

Apart from the obvious matter of taste, are there any advantages or drawbacks to either approach?

For example, I know the stack traces become more readable in the method reference case, which is a small advantage.



via Chebli Mohamed

How upload laravel 5.1 project on server step by step [on hold]

i am upload laravel folder on root server , public file on public_html and routing in index.php set correctly

require __DIR__.'/../bootstrap/autoload.php'; 
$app = require_once __DIR__.'/../bootstrap/app.php';

but not work!error log is empty!! when enter domain nothing show is white page please description how upload laravel 5.1 project on server



via Chebli Mohamed