text:
Q: Users getting 404 when accepting my App invite - why? After creating an iOS app on Facebook, I've tried sending out app invites to FB users. However, the invite directs them to the URL http://www.facebook.com/apps/application.php?id=175116205946673 which is just a 404 page.
I've tried connecting the app to a Community Page in the hope that the invite would send them there instead, but no luck. The app is not in sandbox mode.
I've seen this question asked before, but no solution worked for me. I can't tell the invite to direct users to my Community Page, my App Center page or just my iTunes store page - because I don't know how to manually set the target URL in an invite.

A: Go to Facebook Developer Apps center ,
make sure that 175116205946673 is your app ID and also check:
1.Is your application on? (not sandbox)
2.Is your application authorized?


text:
Q: How can I use a keyboard shortcut from an bash alias or function ? Suppose I have an alias or a function defined in my .bashrc, that is not enough complex to write a single script.
Is it possible to bind that alias/function to the shortcuts facility provided by the graphical interface Gnome or xfce4 ?

A: Not sure about Gnome/XFCE specific options, but [xbindkeys] (https://wiki.archlinux.org/index.php/Xbindkeys) can do this. Configure it with a ~/.xbindkeysrc file and run xbindkeys during your X session.
From the default config file
 # The format of a command line is:
 #    "command to start"
 #       associated key

Where the command can be a shell command, alias, or program (functions didn't seem to work for me).
e.g. I use it to handle my volume keys
"~/apps/pa-vol.sh mute"
   XF86AudioMute
"~/apps/pa-vol.sh minus"
   XF86AudioLowerVolume
"~/apps/pa-vol.sh plus"
   XF86AudioRaiseVolume

Run xbindkeys -k to capture a keystroke for inclusion in your config.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bypassing JWT Authentication in debug mode ASP.NET CORE .NET CORE 2.0 We have a microservice utilizing JWT Tokens to authorize a user when they are requesting data or performing an action in the controller.
Within the controller we have specified that certain Http actions have an [Authorize] attribute on them to prevent certain users from accessing those controller methods.
What we are having difficulty with right now is when we are debugging locally and using swagger, we cannot pass a JWT token nor do we want to have to go  hit the auth service to refresh a token every 15 minutes.
How can i turn off authorization so that the [Authorize] does not do anything when we run locally effectively disabling the Authorization from happening?
Our code is setup as follows:
    services.AddAuthorization(x => x.DefaultPolicy =
                new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser()
                    .Build());
services.AddAuthentication(x =>
            {
                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultSignOutScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(x =>
            {
                x.TokenValidationParameters.ValidateLifetime = true;
                x.TokenValidationParameters.IssuerSigningKey =
                    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtAuthKey));
                x.TokenValidationParameters.ValidateAudience = true;
                x.TokenValidationParameters.ValidateIssuer = true;
                x.TokenValidationParameters.ValidateIssuerSigningKey = true;
                x.TokenValidationParameters.ValidAudience = jwtIssuer;
                x.TokenValidationParameters.ValidIssuer = jwtIssuer;

            });

Then our controller has the authorize attribute on it. No matter what i do it still gives me a 401 unauthorized.
Authorize(Roles="Admin")


text:
Q: Changing MS Exchange Settings through API (rather than dashboard) I am new to Microsoft Exchange Server(2016). I am trying to fetch or change Exchange server mail spam filter settings using API call through the code. However, I have not come across any documentation that helps me with this. What would be the best way to do this? If someone can share documentation with me, it will be great.

A: If you want to change server setting then you will need to use the Exchange Management Shell cmdlets which you can call from Managed code using something like https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/ff326159(v%3Dexchg.140)
The specific cmdlets and examples for the AntiSpam settings can be found in https://learn.microsoft.com/en-us/exchange/antispam-and-antimalware/antispam-protection/configure-antispam-settings?view=exchserver-2019


text:
Q: NIC flashing link-link-link and then dies, then repeats I've got several wall ports that all run down to the same switch - tested them all with ethernet cable checker to make sure the drops were ok and turned out all good.

*

*I can plug in a variety of systems and networking works fine. (Link light on, and then it starts blinking data light)

*But one set of motherboards (Asus X299-A II), their onboard NIC flashes link-link-link (and data light is on) a few times and then lights shut off and then repeats. Of course system never starts communicating.

*If I plug in this troubled NIC (Asus X299-A II) to a switch and plug the switch into the port, links up, starts flashing data, networking is fine.

This troubled system is a Windows system, motherboard: ASUS PRIME X299-A II
Other brand of motherboard, NIC was successful and communicating without switch, plugged right into the ports: X299 UD4 Pro-CF
Has anyone seen this behavior before?


text:
Q: Powershell InputBox (selfmade) only returns "Cancel" `In a Powershell project - small GUI with Winforms - I need a passwordbox. I wrote a test-function but cannot manage to get the correct output ... I only get "Cancel"
I get the same result if I do not use
$inpBox.PasswordChar      = "*"

[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()

function InputForm {

    param($loggedInUser="Spock")

    $inpForm                  = New-Object System.Windows.Forms.Form
    $inpForm.Height           = 120
    $inpForm.Width            = 350
    # $inpForm.Icon             = "$PSScriptRoot\Heidelberg-H.ico"
    $inpForm.Text             = "Authentication Window"
    $inpForm.MaximizeBox      = $false
    $inpForm.MinimizeBox      = $false
    $inpForm.FormBorderStyle  = "FixedDialog"
    $inpForm.StartPosition    = "CenterScreen"  # moves to center of screen
    $inpForm.Topmost          = $true           # Make it Topmost

    # create a Label
    $inpLbl                   = New-Object System.Windows.Forms.Label
    $inpLbl.Width             = 300
    $inpLbl.Location          = New-Object System.Drawing.Point(10,10)
    $inpLbl.Text              = "Please type in the password for user: " + $loggedInUser

    # create a InputBox for the password
    $inpBox                   = New-Object System.Windows.Forms.TextBox
    $inpBox.Width             = 200
    $inpBox.Height            = 25
    $inpBox.PasswordChar      = "*"
    $inpBox.Text              = "********"
    $inpBox.Location          = New-Object System.Drawing.Point(10, 35)

    # create an OK Button
    $inpBtn                   = New-Object System.Windows.Forms.Button
    $inpBtn.Width             = 60
    $inpBtn.Height            = 25
    $inpBtn.Text              = "OK"
    $inpBtn.Location          = New-Object System.Drawing.Point(250,33)
    $form.AcceptButton        = $inpBtn

    $inpForm.Controls.AddRange(@($inpLbl, $inpBox, $inpBtn))

    # OK-Button - Click event
    $inpBtn.Add_Click({

        $inpForm.Close()
        return $inpBox.Text

    })

    $inpForm.ShowDialog()
}

# MAIN

$PW = InputForm (Get-WMIObject -ClassName Win32_ComputerSystem).Username

write-host $PW

A: The problem is with this last part of your function:
$inpBtn.Add_Click({

    $inpForm.Close()
    return $inpBox.Text

})

$inpForm.ShowDialog()

Instead of registering a custom handler for the Click event, you'll want to assign a value to the DialogResult property on the button - then inspect that result and return the value of the textbox from the function:
$inpBtn.DialogResult = 'OK'

if($inpForm.ShowDialog() -eq 'OK'){
    return $inpBox.Text
}
else {
    throw "User canceled password prompt!"
}


text:
Q: error displaying on wordpress website loading I have wordpress website and last week that server was hacked by some hacker group.
While the hosting provider said that all websites are recovered and working fine,  there was an error coming from my website.
"Parse error: syntax error, unexpected end of file, expecting function (T_FUNCTION) in H:\root\home\cmadurawala-001\www\site1\wp-includes\class-wp-hook.php on line 492"

I need to resolve this. If anyone can help me

A: If your Site is working Properly then you can turn off that PHP errors.
Inside your wp-config.php file, look for the following line:
define('WP_DEBUG', true);

It is also possible, that this line is already set to false. In that case, you'll see the following code:
 define('WP_DEBUG', false);

In either case, you need to replace this line with the following code:
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);


text:
Q: Move square inside large matrix, find minimum number in overlapping I have a sqaure matrix and a smaller square which moves inside the matrix at all possible positions (does not go out of the matrix). I need to find the smallest number in all such possible overlappings.
The problem is that the sizes of both can go upto thousands. Any fast way to do that?
I know one way - if there's an array instead of a matrix and a window instead of a square, we can do that in linear time using a deque.
Thanks in advance.
EDIT: Examples
Matrix:
1 3 6 2 5
8 2 3 4 5
3 8 6 1 5
7 4 8 2 1
8 0 9 0 5

For a square of size 3, total 9 overlappings are possible. For each overlapping the minimum numbers in matrix form are:
1 1 1
2 1 1
0 0 0

A: It is possible in O(k * n^2) with your deque idea:
If your smaller square is k x k, iterate the first row of elements from 1 to k in your matrix and treat it as an array by precomputing the minimum of the elements from 1 to k, from 2 to k + 1 etc in each column of the matrix (this precomputation will take O(k * n^2)). This is what your first row will be:
*********
1 3 6 2 5
8 2 3 4 5
3 8 6 1 5
*********
7 4 8 2 1
8 0 9 0 5

The precomputation I mentioned will give you the minimum in each of its columns, so you will have reduced the problem to your 1d array problem.
Then continue with the row of elements from 2 to k + 1:
1 3 6 2 5
*********
8 2 3 4 5
3 8 6 1 5
7 4 8 2 1
*********
8 0 9 0 5

There will be O(n) rows and you will be able to solve each one in O(n) because our precomputation allows us to reduce them to basic arrays.


text:
Q: APC not storing data from MySQLi result array I'm havin trouble storing an array of data. Below is the code use in the web application to check to see if the data is there, and if it's there serve it, else, cache it then serve it. I am using MySQLi
$id = $db->real_escape_string($_GET['id']);
$key = 'content_' . $app;
$data = apc_fetch($key);
if (!is_array($data)) {
    $result = $db->query("SELECT * FROM pages_content WHERE id = $id");
    $rawdata = $result->fetch_assoc();
    $data = $result->fetch_array(MYSQLI_ASSOC);
    apc_store($key, $data);
    echo "<!-- DATA_NOT_FOUND_AND_STORED-- >";
}

Can you see what I'm doing wrong?
Thanks

A: I've solved it.
$key was not set correctly.


text:
Q: Make Ubuntu Server use less swap and more actual RAM I have a server with 128 GB of RAM and a 100 GB hard drive in it. It seems to use pretty much swap instead of using actual RAM when rsyncing disks. I found other questions on Stack Overflow with similar problems, but none had a real solution. This is the output of "glances":

The server will normally never use 128 GB of RAM, so is it safe to disable swap? Would this increase the speed of the system or could it break something?
Or can I tell Ubuntu to use the physical RAM, instead of using swap?

A: On your Ubuntu server you have a total of 1,38 GB of swap for 128 GB of RAM.
On your screenshot the system is using 970 MB of swap for 14,9 GB of RAM, to my opinion is a standard amount of swap used by the system and far less to the 14,9 GB of RAM.
However it's a fair point to avoid your linux kernel to swap because is actually an "expensive" process in regard to its overall impact on the system performance.
Here I would suggest to adjust the amount of swappiness on the system, please find the following information for the Ubuntu FAQ :

What is swappiness and how do I change it?
The swappiness parameter controls the tendency of the kernel to move
  processes out of physical memory and onto the swap disk. Because disks
  are much slower than RAM, this can lead to slower response times for
  system and applications if processes are too aggressively moved out of
  memory.

*

*swappiness can have a value of between 0 and 100

*swappiness=0 tells the kernel to avoid swapping processes out of
  physical memory for as long as possible

*swappiness=100 tells the kernel to aggressively swap processes out of
  physical memory and move them to swap cache
The default setting in Ubuntu is swappiness=60. Reducing the default
  value of swappiness will probably improve overall performance for a
  typical Ubuntu desktop installation. A value of swappiness=10 is
  recommended, but feel free to experiment. Note: Ubuntu server
  installations have different performance requirements to desktop
  systems, and the default value of 60 is likely more suitable.
To check the swappiness value
cat /proc/sys/vm/swappiness
To change the swappiness value A temporary change (lost on reboot)
  with a swappiness value of 10 can be made with
sudo sysctl vm.swappiness=10
To make a change permanent, edit the configuration file with your
  favorite editor:
gksudo gedit /etc/sysctl.conf
Search for vm.swappiness and change its value as desired. If vm.swappiness does >not exist, add it to the end of the file like so:
vm.swappiness=10
Save the file and reboot.


text:
Q: Android Studio path Hey Guys I did a little App, where  I type into a textbox a specific value (height, weight) and save it into a file.
I did this but I do not know, which path I have to use for Android.
Hope you can help :)
 public void SaveList(View view) {
        //Pf`enter code here`ad, im privaten Speicherbereich
        File file = new File("I need this path :)");
        try {
            OutputStreamWriter fdg = new OutputStreamWriter(new FileOutputStream(file));
            fdg.write(""+this.weight);
            fdg.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

A: You can use Environment.getDataDirectory() to get the root directory, if you dont have an SD card.
If you have an SD card, use Environment.getExternalStorageState()
Read more about them in the docs
Thus, change your code as follows
File file = new File(Environment.getDataDirectory()+"/your_folder_name/your_file_name");

This will create a file with name your_file_name in the folder your_folder_name in your internal storage.


text:
Q: How to plot figures in VSCode in a silent manner? I am new to VSCode and have a question related to the plotting issues. When I plot a large number of figures, like 100, how to plot silently and prevent figures jumping out one by one? I would appreciate it very much if you could give me some suggestions on this.

A: You can read this issue on github.
This feature actually exists already in our Jupyter Notebooks editor.
Or you can define Jupyter-like code cells within Python code using a # %% comment:
# %%
msg = "Hello World"
print(msg)


text:
Q: Wordpress: How can I keep market checkboxes in searchform after submit? I created a custom post type with custom taxonomies and a function for get terms of taxonomies in checklist. In searchform I call this function in accordion. My problem is when I like keep market checkboxes in searchform. The theme is a child theme Avada.How can I do it?
My functions.php

/*===================================================
Show taxonomies in checklist
=====================================================*/
function get_terms_checklist($taxonomies, $args){
 $myterms = get_terms($taxonomies, $args);
 $output ="<fieldset name='".$taxonomies."'>
";
 foreach($myterms as $term){
  $root_url = get_bloginfo('url');
  $term_taxonomy=$term->taxonomy;
  $term_slug=$term->slug;
  $term_name =$term->name;
  $link = $term_slug;
  $key=$taxonomies;
  $output .="
<input name='".$key."' type='checkbox' value='".$link."' />".$term_name."
";
 }
 return $output;

My searchform.php

/*General Accordion****************************************************************************/
/*Set style of open slide*/
.accordion section:target { background:#FFF; padding:10px;}
.accordion section:target:hover { background:#FFF; }
.accordion section:target h3 {width:90%;}
.accordion section:target h3 a{ color:#333; padding:0;}
.accordion section:target p {display:block;}
.accordion section h3 a{padding:18px 20px;display:block; font-size:14px; font-weight:normal;color:#eee; text-decoration:none; }

/*set style of closed slide*/
.accordion section{ float:left;overflow:hidden; color:#333; cursor:pointer; background: #333; margin:3px; }
.accordion section:hover {background:#444;}
.accordion section p { display:none; }
.accordion section:after{position:relative;font-size:14px;color:#000;font-weight:bold;}
.accordion section:nth-child(1):after{content:'1';}
.accordion section:nth-child(2):after{content:'2';}
.accordion section:nth-child(3):after{content:'3';}
.accordion section:nth-child(4):after{content:'4';}
.accordion section:nth-child(5):after{content:'5';}
.accordion section:nth-child(6):after{content:'6';}
.accordion section:nth-child(7):after{content:'7';}
/*End General Accordion****************************************************************************/
/*Vertical Accordion *************************************************************************/
.vertical section{ width:100%; height:40px;
 -webkit-transition:height 0.2s ease-out;
 -moz-transition:height 0.2s ease-out;
   -o-transition:height 0.2s ease-out;
 -ms-transition:height 0.2s ease-out;
   transition:height 0.2s ease-out;
}
/*Set height of the slide*/
.vertical :target{ height:600px; width:97%; }

.vertical section h3 { position:relative; left:0; top:-5px; }

/*Set position of the number on the slide*/
.vertical section:after{ top:-60px;left:810px;}
.vertical section:target:after{ left:-9999px;}

<form class="search" id="searchform" action="<?php echo home_url(); ?>/" method="get">

 <?php $search_text = __(" " ); ?>

 <input type="text" class="field"  value="<?php echo $search_text; ?>" onblur="if (this.value == '')  {this.value = '<?php echo $search_text; ?>';}" onfocus="if (this.value =='<?php echo get_search_query() ?>')  {this.value = '<?php echo get_search_query() ?>';} {this.name = 's';}" />

    <?php
    $taxonomies = 'ciutats';
    $args =array('orderby'=>'name','hide_empty'=>true);
    $ciutat_select=get_terms_checklist($taxonomies, $args);
    ?>

 Escull la ciutat

<?php echo $ciutat_select; ?>

     <?php
    $taxonomies = 'districtes';
    $args = array('orderby'=>'name','hide_empty'=>true);
    $districte_select = get_terms_checklist($taxonomies, $args); ?>

Escull el districte

<?php echo $districte_select; ?>

  <?php
  $taxonomies = 'barris';
  $args = array('orderby'=>'name','hide_empty'=>true);
  $barri_select = get_terms_checklist($taxonomies, $args); ?>

 Escull el barri

<?php echo $barri_select; ?>

   <?php
   $taxonomies = 'ambits';
      $args = array('orderby'=>'name','hide_empty'=>true);
   $ambit_select = get_terms_checklist($taxonomies, $args); ?>

 Escull l'àmbit

<?php echo $ambit_select;?>

   <?php
   $taxonomies = 'colectius';
   $args = array('orderby'=>'name','hide_empty'=>true);
   $colectiu_select = get_terms_checklist($taxonomies, $args); ?>

 Escull el col.lectiu

<?php echo $colectiu_select; ?>

  <?php
  $taxonomies = 'serveis';
  $args = array('orderby'=>'name','hide_empty'=>true);
  $servei_select = get_terms_checklist($taxonomies, $args); ?>

 Escull el servei

<?php echo $servei_select; ?>

 <?php
 $taxonomies = 'especificitatserveis';
 $args = array('orderby'=>'name','hide_empty'=>true);
    $especificitatservei_select = get_terms_checklist($taxonomies, $args);
    ?>

  Escull l'especificitat del servei

<?php echo $especificitatservei_select; ?>

   <input type="submit" id="searchsubmit" value="" />

    </form>

A: Since your form method is get, all of these selections should be available to php in the $_GET superglobal or via javascript (read this SO thread ).
Note that you shouldn't trust anything in $_GET directly. Always sanitize the data using either a Wordpress or php function.

A: My functions php:

/*===================================================
Show taxonomies en checklist
=====================================================*/
function get_terms_checklist($taxonomies, $args){
$myterms = get_terms($taxonomies, $args);
$output ="<fieldset name='".$taxonomies."'>
";
foreach($myterms as $term){
$root_url = get_bloginfo('url');
$term_taxonomy=$term->taxonomy;
$term_slug=$term->slug;
$term_name =$term->name;
if ((isset($_GET[$taxonomies])) && ($term_slug==$_GET[$taxonomies]))
 {$output .="
<input name='".$taxonomies."' type='checkbox' value='".$term_slug."' checked/> ".$term_name."
"; }
else {$output .="
<input name='".$taxonomies."' type='checkbox' value='".$term_slug."' /> ".$term_name."
";}
}
return $output;
}


text:
Q: Rails check if field value is the default value for that field I have a field named number on the Address model, which has a default of 0 set at database level. If I do Address.new.number, I will get 0 back.
Now, I want to trigger a before_create callback only if number != <default value>. So, I will have before_create :callback, unless: <condition>. How can I check this using some Rails "logic"? I know I can compare to 0, but I'd rather compare to a dynamical value, as retrieved by Rails.

A: Default values are accessible in Address.column_defaults as a hash of {"column" => default}:
Address.column_defaults
#=> {"number" => 0, "street" => nil, ...}

You can also use the <attribute>_changed? methods Rails provides. This will be false unless you initialize the object with a non-default value.
Address.new.number_changed? #=> false
Address.new(number: 1).number_changed? #=> true

So your before_create can look like:
before_create :callback, if: :number_changed?

A: what about using the columns has?
Address.columns_hash['number'].default

should give you want
so maybe something like this
before_create :callback, unless: Proc.new { |address| address.number == Address.columns_hash['number'].default }

But this seems kinda odd over using something like number_changed?


text:
Q: iOS Swift - Question about semaphores and sequencing in Bluetooth Low Energy Manager I'm looking at the open source Bluefruit code as an example, specifically the BleManager class that is the interface with the CBCentralManager. I've emailed the author and they didn't respond:
Bluefruit BleManager class
It looks like the class is designed in a singleton architecture ("shared" on line 23) and so is constructed lazily when the first "BleManager.connect() is called elsewhere in the code.
What confuses me is in the init(), there's a semaphore "wait" function:
override init() {
    super.init()

    centralManagerPoweredOnSemaphore.wait()
    centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.global(qos: .background), options: [:])
//        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main, options: [:])
    }

I'm really only used to semaphores in a DispatchQueue.async() thread. Isn't this wait() function being called on a main thread? Won't that lock it up? The .signal() call that will unblock that .wait() call is on line 289:
extension BleManager: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {

        DLog("centralManagerDidUpdateState: \(central.state.rawValue)")
        // Unlock state lock if we have a known state
        if central.state == .poweredOn || central.state == .poweredOff || central.state == .unsupported || central.state == .unauthorized {
            centralManagerPoweredOnSemaphore.signal()
        }

So once the system centralManager updates the BLE utility state, this will get called, and as long as it's not unknown, .signal() will get called and the rest of the init() will run. I've used print statements to confirm this is how it works. centralManagerPoweredOnSemaphore.wait() is called, then centralManagerDidUpdateState(), and then the rest of the init(). I still don't understand this though:

*

*How did did the semaphore .wait() on the main thread not lock everything up? For example look at line 169 and 170. What does that do?

*How is centralManagerDidUpdateState() called when the delegate hasn't been assigned yet? It seems like the delegate gets assigned in the bottom of the init() that isn't called right away before this function. How does the system CBCentralManager know to use that specific centralManagerDidUpdateState() function?

*How exactly do the CBCentralManager states work? I've read through the official documentation but it's not too descriptive. It seems that when "Core Bluetooth initializes or resets" it will be "unknown". And then after a certain period of time, will it always change to a known state, based on if the device has the capability and what the user settings/permissions are? So I'm guessing that's why it's "safe" to block the rest of the class until we get a response. But what "initializes" the Core Bluetooth in this case? As far as I can tell, with the partial init() and before centralManagerDidUpdateState(), there were no calls to any Core Bluetooth functions. What made Core Bluetooth try to initialize the BLE utility and update the state? It looks like this BleManager class is called lazily, so it can't have been anything at a higher level.

In the end it works though, I just wonder how the exact sequence of things is actually running under the hood to make it run properly.

A: They are using the semaphore to block any operations on the BleManager object until the central exits the .unknown state.
The semaphore is created with an initial value of 1. The wait in the init will decrement it to 0, and not block. The central is then initialised and at some point the powered on state is entered.  At this point the signal will return the semaphore to 1.
Now looking at the other functions, such as the connect function (line 167) you will see the first thing they do is wait and then signal the semaphore. Consider what happens in two different states:

*

*The central is not yet in the .poweredOn state - the semaphore count is 0 so the wait blocks. Assuming the BLE state becomes .poweredOn at some point, the wait will end and the semaphore is immediately released and then the connect function proceeds.

*The central is already in the .poweredOn state - the semaphore count is 1, so the wait does not block, the semaphore is then immediately released and the connect function proceeds.

The other functions work in a similar way.
The advantage of this approach is that the calling code doesn't need to keep checking the state; it can access the sharedInstance and then immediately call startScan without needing to check that the Central is powered on.


text:
Q: Swift Delegates and Protocol I am learning swift protocol and delegate pattern.But,I really need help with the following problem which return me empty results
At ViewController 1 :
protocol GetAllDataProtocol{
     func didReadInfo(info : [[String:String]])
}
class ViewController1 : {
     var delegate : GetAllDataProtocol?
     var info_data : [[String:String]] = []

     override func viewDidLoad() {

         readData()
     }

     func readData(){
         info_data.append(["ID" :"234FD","ADDRESS":"Maimi","TYPE":"A"])
         delegate?.didReadInfo(info_data)
     }
}

Then at ViewController 2 :
class SubmissionViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,GetAllDataProtocol{
      var info_data = [[String:String]]()

      @IBAction func submitTapped(sender: AnyObject) {
           print("After : \(info_data)")
      }

      func didReadInfo(info: [[String : String]]) {
           dispatch_async(dispatch_get_main_queue(),{
               self.info_data = info
               print("Before : \(self.info_data)")
           })
      }
}

When it run
After : []

Why it didnt run "before?" and why i can't get the data.

A: SubmissionViewController should have referenece on ViewController1. In viewDidLoad() method assign viewController.delegate to self.
The code:
class SubmissionViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,GetAllDataProtocol{
    var info_data = [[String:String]]()
    var viewController1:ViewController1?

    override func viewDidLoad() {
        //You should here load viewController1 or connect it by outlet in above
        let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
        viewController1 = storyboard.instantiateViewControllerWithIdentifier("ViewController1") as? ViewController1
        self.viewController1!.delegate = self
    }
    @IBAction func submitTapped(sender: AnyObject) {
        print("After : \(info_data)")
    }

    func didReadInfo(info : [[String:String]]) {
        dispatch_async(dispatch_get_main_queue(),{
            self.info_data = info
            print("Before : \(self.info_data)")
        })
    }
}

A: You aren't setting the reference of the delegate as Ahmed Lotfy explained.
Maybe you are missing the point that a protocol only is a kind of a template or commitment. So if you define a protocol with your function
 func didReadInfo(info : [[String:String]])

you are saying "Hey, every class that conforms to the protocol XYZ should have implemented this method." And by declaring a delegate variable on your "ViewController1" class that should be conform to protocol "GetAllDataProtocol", you just ensure that you can call the function "didReadInfo" on that object. But this variable is not set anywhere, thats why your call
delegate?.didReadInfo(info_data)

has no effect. The optional chaining of "delegate?." does not succeeds and the function "didReadInfo" is never called.


text:
Q: Issue retrieving JSON response for ASP.NET Core REST API I have referenced the below link and tried to create a POC app:
https://techcommunity.microsoft.com/t5/azure-sql-blog/10k-request-per-second-rest-api-with-azure-sql-dapper-and-json/ba-p/1189675
    [HttpGet("{a}/{b}", Name = "TestMethod")]
    [ProducesResponseType(201)]
    [ProducesResponseType(400)]
    [ProducesResponseType(500)]
    public async Task<JsonElement> TestMethodAsync(long a, long b)
    {
        return await _repo.GetDataAsync(a);
    }

public async Task<JsonElement> GetDataAsync(long a)
{
    JsonDocument result = null;
    const string sql = @"SELECT HC.LeadReviewerEmailAddress, HCRT.ReviewerEmailAddress,
                                ER.PartnerEmailAddress, ER.GroupAuditPartnerEmailAddress, ETM.EmailAddress
                         FROM [EM].[HealthCheck] HC
                         JOIN [EM].[EngagementReview] ER ON ER.EngagementReviewId = HC.EngagementReviewId
                         LEFT JOIN [EM].[HealthCheckReviewTeam] HCRT ON HC.HealthCheckId = HCRT.HealthCheckId
                         LEFT JOIN  [EM].[EngagementTeamMember] ETM ON ETM.EngagementReviewId = HC.EngagementReviewId
                         WHERE HC.HealthCheckId=@a FOR JSON PATH, WITHOUT_ARRAY_WRAPPER";
    var param = new{a};

    using (var conn = await _dapperService.CreateConnection())
    {
        var queryResponse = await conn.QueryAsync<string>(sql, param);
        var allTeamMembersForHC = queryResponse.FirstOrDefault();

        if (!string.IsNullOrWhiteSpace(allTeamMembersForHC))
        {
            result = JsonDocument.Parse(allTeamMembersForHC);
        }
    }

    if (result == null)
        result = JsonDocument.Parse("[]");

    return result.RootElement;
}

On validating the above method I am getting the below response instead of the JSON string:
{
  "valueKind": 2
}

Can anyone help me to resolve this issue?

A: when using FOR JSON the resultset has only one column and one row, so you have to use the method ExecuteScalarAsync instead of QueryAsync


text:
Q: How can you override Mage_Adminhtml_Permissions_UserController Most of today I have been trying to override Mage controller and I have no ideas what I'm doing wrong. Does anyone can help me.
app/code/local/Fox/Extacl/etc/config.xml
<modules>
    <Fox_Extacl>
        <version>0.1.0</version>
    </Fox_Extacl>
</modules>
<global>
    <models>
        <admin>
            <rewrite>
                <session>Fox_Extacl_Model_Session</session>
            </rewrite>
        </admin>
    </models>
    <blocks>
        <adminhtml>
            <rewrite>
                <permissions_user_edit_tab_roles>Fox_Extacl_Block_Permissions</permissions_user_edit_tab_roles>
            </rewrite>
        </adminhtml>
    </blocks>
</global>
<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <Fox_extacl before="Mage_Adminhtml">Fox_Extacl_Adminhtml</Fox_extacl>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

app/code/local/Fox/Extacl/controllers/Adminhtml/UserController.php
<?php
require_once('/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php');
class Fox_Extacl_Adminhtml_UserController extends Mage_Adminhtml_Controller_Action
{

public function saveAction()
{
    if ($data = $this->getRequest()->getPost()) {
        echo '<pre>';
        print_r($data);

    }
    // $this->_redirect('*/*/');
}
}

Thank you in advance.

A: Since your trying to put your module before Adminhtml
Try
require_once('/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php');
class Fox_Extacl_Adminhtml_Permissions_UserController extends Mage_Adminhtml_Permissions_UserController
{

A: You need to rename your Controller to UserController.
This controller should listen to the route:
/<whateverYourAdminDirIs>/extacl/

A: First change this from config.xml
<Fox_extacl before="Mage_Adminhtml">Fox_Extacl_Adminhtml</Fox_extacl>

to
<Fox_Extacl before="Mage_Adminhtml">Fox_Extacl_Adminhtml</Fox_Extacl>

Now here is how the controller rewrite work.
You requested admin/permissions_user/something.
Magento looks in all the folders mapped to the adminhtml router for this file  Permissions/UserController.php.
So in your case, you need to place the file in app/code/local/Fox/Extacl/controllers/Adminhtml/Permissions/UserController.php. You are missing the Permissions folder.
And since you are extending a controller and not replacing it, you should make your class extend the original controller.
require_once '/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php';
class Fox_Extacl_Adminhtml_Permissions_UserController
    extends Mage_Adminhtml_Permissions_UserController
{...}


text:
Q: Upload file to database with file link I am working on a project whereby the user has to upload a document. I have successfully been able to upload a file to the database and serve the user the uploaded file. I however want to upload files to the database using the file link rather than just selecting file from your device.
models.py
class Books(models.Model):
    title = models.CharField(max_length=500, default="")
    author = models.CharField(max_length=500, default="")
    publication = models.CharField(max_length=500, default="")
    edition = models.IntegerField(default="")
    is_available = models.BooleanField()
    book = models.FileField(
        default="",
        upload_to="books",
        validators=[validate_book_extension],
        verbose_name="books",
    )
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="")

    class Meta:
        verbose_name_plural = "Books"

    def __str__(self):
        return self.title

views.py
def books(request):
    genres_names = Genre.objects.all()
    if request.method == "POST":
        form = BookFile(request.POST, request.FILES)
        files = request.FILES.getlist("book")
        genres_name = request.POST.get("genres")
        try:
            if form.is_valid():
                new_old_genre, created = Genre.objects.get_or_create(
                    genres=genres_name.lower()
                )
                genre = Genre.objects.filter(genres=genres_name)
                if files:
                    for f in files:
                        names = str(f)
                        name = names.strip(".pdf")
                        Books.objects.create(
                            genre=new_old_genre, book_title=name, book=f
                        )
                return redirect(index)
        except IntegrityError:
            messages.error(request, "value exist in database")
            return redirect(books)
    else:
        form = BookFile()
    return render(request, "books.html", {"form": form, "genres_names": genres_names})

forms.py
class BookInfo(forms.ModelForm):
    class Meta:
        model = Genre
        fields = [
            "genres",
        ]
        widgets = {"genres": forms.TextInput(attrs={"list": "genres"})}

class BookFile(BookInfo):
    book = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True}))

    class Meta(BookInfo.Meta):
        fields = BookInfo.Meta.fields + [
            "book",
        ]

HTML template
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Books</title>

    <form action="/books/" method="POST" enctype='multipart/form-data'>
        {% csrf_token %}
        {% if request.user.is_authenticated %}

                {{form.book}}

                {{form.genres}}
                <datalist id="genres">
                    <select name="" id="">
                        {% for name in genres_names %}
                        <option value="{{name.genres}}">{{name.genres}}</option>
                        {% endfor %}
                    </select>
                </datalist>

                <input type="submit" value="Create">

                <input type="button" value="SignOut">

                {{form.errors}}

            {% for message in messages %}

{{ message }}

            {% endfor %}
        {% endif %}
    </form>

So please how do I go about it

A: Actually, Django does just that. It takes the file and uploads it to the specified directory in your models. In your case, that is books/. Afterward, it uploads the file path (link) to the database.

A: You can modify Queryset dictionary values like this...
models.py
class DEMOClass(models.Model):
      field1 = models.CharField(max_length=255, null=True,blank=True)
      field2 = models.ImageField(upload_to='Images')

      def __str__(self):
            return self.field1

views.py
def InsertData(request):
    data = DEMOClass.objects.values('field1','field2')
    print('------ Before ------')
    print(data)
    for i in data:
        i.update({'field2':str(request.build_absolute_uri(i['field2']))})
    print('------ After ------')
    print(data)

Output
------ Before ------
<QuerySet [{'field1': 'test', 'field2': 'Images/download_rBWYYCh.jpg'}]>
------ After ------
<QuerySet [{'field1': 'test', 'field2': 'http://127.0.0.1:8000/Images/download_rBWYYCh.jpg'}]>


text:
Q: Stopping the execution of threads in Python. The thread is blocked before join method I'm writing the program which execute child programs in a new process and read stdout of these programs in the separate thread and write it in StyledTextCtrl control. I faced with problem of stopping the execution of threads. I have the following code:
import subprocess
from threading import Thread, Lock
import wx
import wx.stc

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] (%(threadName)-10s) %(module)10s:%(funcName)-15s %(message)s',
                    )

class ReadThread(Thread):
    def __init__(self, subp, fd, append_text_callback):
        Thread.__init__(self)
        self.killed = False
        self.subp = subp
        self.fd = fd
        self.append_text_callback = append_text_callback

    def run(self):
        chunk = None
        while chunk != '' and not self.killed:
            self.subp.poll()
            chunk = self.fd.readline()
            if chunk:
                self.append_text_callback('%d: ' % self.subp.pid + chunk)
            if chunk == "":
                break
        logging.debug('END')

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Example1")
        panel = wx.Panel(self, wx.ID_ANY)
        self.log = wx.stc.StyledTextCtrl(panel, wx.ID_ANY, size=(300,100), style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
        run_button = wx.Button(panel, wx.ID_ANY, 'Run')
        self.Bind(wx.EVT_BUTTON, self.onRun, run_button)
        self.Bind(wx.EVT_CLOSE, self.OnCloseFrame)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.log, 1, wx.ALL|wx.EXPAND, 5)
        sizer.Add(run_button, 0, wx.ALL|wx.CENTER, 5)
        panel.SetSizer(sizer)
        self.read_thread_1 = None
        self.read_thread_2 = None
        self.log_lock = Lock()

    def OnCloseFrame(self, event):
        logging.debug('CLOSE')
        if self.read_thread_1:
            self.read_thread_1.killed = True
        if self.read_thread_2:
            self.read_thread_2.killed = True
        if self.read_thread_1:
            self.read_thread_1.join(timeout=1)
            logging.debug('after 1 join')
        if self.read_thread_2:
            self.read_thread_2.join(timeout=1)
            logging.debug('after 2 join')
        self.read_thread_1 = None
        self.read_thread_2 = None
        event.Skip()

    def onRun(self, event):
        cmd1 = "E:/threading_block/stdout_emulator.exe 50 500"
        subp1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.read_thread_1 = ReadThread(subp1, subp1.stdout, self.AppendText)
        self.read_thread_1.start()
        cmd2 = "E:/threading_block/stdout_emulator.exe 21 400"
        sp2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.read_thread_2 = ReadThread(sp2, sp2.stdout, self.AppendText)
        self.read_thread_2.start()
        logging.debug('END')

    def AppendText(self, text):
        self.log_lock.acquire()
        logging.debug('%s' % text)
        self.log.AddText(text)
        self.log_lock.release()

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm().Show()
    app.MainLoop()

I stop the threads in OnCloseFrame method. I set killed attribute in True value and as a result it cause the finishing the execution of while loop in run method of ReadThread class.
There is no problem when I close this application (under Windows) during the execution of threads. But If I remove timeout=1 from self.read_thread_1.join(timeout=1) and self.read_thread_2.join(timeout=1) there will be a blocking of program.
The program stuck before self.read_thread_1.join() in OnCloseFrame method.
What's the problem with this blocking? Why I should use timeout for join?
The C code of std_emulator.exe is the following:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <time.h>

int main(int argc, char *argv[])
{
  int s;
  int n;
  if (argc > 1)
  {
    s = atoi(argv[1]);
    n = atoi(argv[2]);
  }
  else
  {
    s = 1;
    n = 50;
  }

  int i;
  for (i = s; i < n; ++i)
  {
    printf("This is %d line\n", i);
    fflush(stdout);
    if (i % 2 == 0)
    {
      srand(time(NULL));
      int r = rand() % 7;
      printf("sleep_type_2 with %d\n", r);
      Sleep(30 * r);
      fflush(stdout);
    }
      if (i % 3 == 0)
      {
        int r = rand() % 7;
        printf("sleep_type_3 with %d\n", r);
        Sleep(40 * r);
        fflush(stdout);
      }
      if (i % 5 == 0)
      {
        int r = rand() % 9;
        printf("sleep_type_5 with %d\n", r);
        Sleep(50);
        fflush(stdout);
      }
    }
}

A: In your case, you're not actually killing the threads when you use join(timeout=1). Instead, the join operation is waiting for one second to see if the thread exits, and when it doesn't, it just gives up. The join won't work because your thread is most likely blocking on this line:
chunk = self.fd.readline()

So it's never looping around to see if killed has been set to True. I think the best way for you to cleanly shutdown the threads is to terminate the subprocess being run in ReadThread in OnCloseFrame:
if self.read_thread_1:
    self.read_thread_1.subp.terminate()
    self.read_thread_1.join()
if self.read_thread_2:
    self.read_thread_2.subp.terminate()
    self.read_thread_2.join()

Terminating the subprocess will unblock the readline call, and allow you to cleanly terminate the thread.


text:
Q: SSIS Pass Datasource Between Control Flow Tasks I'm having troubles solving this little problem, hopefully someone can help me.
In my SSIS package I have a data flow task.
There's several different transforms, merges and conversions that happen in here.
At the end of the dataflow task, there is two datasets,  one that contains two numbers that need to be compared,  and another dataset that contains a bunch of records.
Ideally, I would like to have these passed onto a whole new data flow task (separate sequence container) where I can do some validation work on it and separate the logic.
I cant for the life of me figure out how to do it.  Iv tried looking into scripting and storing the datasets as variables, but I'm not sure this is the right way to do it.
The next step is to export the large dataset as a spreadsheet,  but before this happens i need to compare the two numbers from the other dataset and ensure they're correct.

A: To pass data flowing in one dataflow to another, You have to have a temporary location.
This means that You have to put data in destination in one dataflow and then read that data in another dataflow.
You can put data in number of destinations:

*

*database table

*raw file

*flat file

*dataset variable (recordset destination)

*any other destination component that you can read from with corresponding source component or by writing script or whatever

Raw files are meant to be used for cases like this. They are binary and as such they are extremely fast to write to and read from.
In case You insist to use recordset destination take a look at http://consultingblogs.emc.com/jamiethomson/archive/2006/01/04/SSIS_3A00_-Recordsets-instead-of-raw-files.aspx because there is no recordset source component.

A: A Data Flow Task needs to have a destination; a Data Flow Task likewise is NOT a destination. Otherwise the data doesn't go anywhere in the pipeline. From my experience, your best bets are to:
1) Pump the data into staging tables in SQL Server, and then pick up the validations from there.
2) Do the validations in the same Data Flow task.


text:
Q: EditText box contents into ListView on Android after clicking Button Would like to see if someone can help me on figuring out how to add the contents of a EditText box into a ListView list on Android. I have a project I'm working on that, uses Barcode Scanner to scan a barcode, and return the results into the EditText box.
I'm now attempting to code the contents of the EditText box with the use of a button to add the contents in the list either within that activity or on another one. I've looked at the simple note list example and a couple of other examples, however, when I try and implement some of the same concepts, I get no where or I think I get somewhere, but the code does nothing. I'm sorry it's late.. been up all night trying to figure this out...
Any help, advice, is greatly and always appreciated...
package com.terrellmcqueen.databaseproject474;

import java.util.ArrayList;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class Main extends Activity implements OnClickListener {
    private static final int REQUEST_BARCODE = 0;
    private TextView mBarcodeEdit;
    private TextView mScanButton;

    // private fields omitted

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mBarcodeEdit = (EditText) findViewById(R.id.myEditText);
        mScanButton = (Button) findViewById(R.id.scanButton);
        mScanButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.scanButton:
                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                intent.putExtra("SCAN_MODE", "SCAN_MODE");
                startActivityForResult(intent, REQUEST_BARCODE);
                break;
        }
     }

     public void onClick1(View v) {
         switch (v.getId()) {
             case R.id.btnSimple:
                 ListView myListView = (ListView) findViewById(R.id.myListView);
                 final EditText myEditText = (EditText) findViewById(R.id.myEditText);
                 final ArrayList<String> noteList = new ArrayList<String>();
                 final ArrayAdapter<String> aa;

                 // binding an array of Strings
                 aa = new ArrayAdapter<String>(this,
                         android.R.layout.simple_list_item_1,noteList);

                 // here we set the adapter, this turns it on
                 myListView.setAdapter(aa);

                 // here is the button
                 // Button btnSimple = (Button) findViewById(R.id.btnSimple);

                 //  String barcode = mBarcodeEdit.getText().toString();

                 //  String title = mTitleEdit.getText().toString();
                 //  String price = mPriceEdit.getText().toString();
            }
      }

    public void onActivityResult(int requestCode,int resultCode, Intent intent) {
        if (requestCode == REQUEST_BARCODE) {
            if (resultCode == RESULT_OK) {
                String barcode = intent.getStringExtra("SCAN_RESULT");
                mBarcodeEdit.setText(barcode);
            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }
}

A: In the button click event, add the editText's text to the list used to populate the ListView and call the notifyDataSetChanged() of your ArrayAdapter. Hope that would work.
noteList.add(mBarcodeEdit.getText());
aa.notifyDataSetChanged();

A: I have changed the code little bit and it's working according to your requirement please look at the same
package com.barcode;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class BarcodeActivity extends Activity implements OnClickListener {
    private static final int REQUEST_BARCODE = 0;
    private TextView mBarcodeEdit;
    private Button mScanButton;
    private Button mAddButton;

    // private fields omitted

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mBarcodeEdit = (EditText) findViewById(R.id.editText1);
        mScanButton = (Button) findViewById(R.id.button1);
        mAddButton = (Button) findViewById(R.id.add);
        mScanButton.setOnClickListener(this);
        mAddButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "SCAN_MODE");
            startActivityForResult(intent, REQUEST_BARCODE);
            break;
        case R.id.add:
            ListView myListView = (ListView) findViewById(R.id.listView1);
            final EditText myEditText = (EditText) findViewById(R.id.editText1);
            final ArrayList<String> noteList = new ArrayList<String>();
            noteList.add(myEditText.getText().toString());
            final ArrayAdapter<String> aa;

            // binding an array of Strings
            aa = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, noteList);

            // here we set the adapter, this turns it on
            myListView.setAdapter(aa);
            break;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_BARCODE) {
            if (resultCode == RESULT_OK) {
                String barcode = intent.getStringExtra("SCAN_RESULT");
                mBarcodeEdit.setText(barcode);
            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }
}


text:
Q: Pandas or matplotlib falsely shifts x-values when combining multiple dataframes with different indices into single plot How can I plot these two CSV files into the same graph using pandas?
# df1.csv
T,100,200,300,400,500,600,700,800,900,1000
10^17,0.000395514,0.00111554,9.75478e-05,8.82842e-05,0.000195049,0.000168988,0.000107534,6.45815e-05,4.65528e-05,4.91799e-05
10^18,0.0015543,0.00529097,0.00775261,0.00279436,0.000279994,1.10931e-05,7.38623e-07,4.41783e-06,8.23956e-06,1.72932e-05
10^19,0.00313802,0.0155777,0.030378,0.0410598,0.0377613,0.0207677,0.00835572,0.00326071,0.00135329,0.000599954
10^20,0.0027506,0.022583,0.0591009,0.0967276,0.123353,0.133666,0.126835,0.106393,0.0806346,0.058811
10^21,0.0024868,0.0213928,0.0536278,0.0904901,0.124033,0.148728,0.162047,0.164976,0.162849,0.165446

# df2.csv
T,zT
298.52,0.42262
322.04,0.33321
370.95,0.18304
420.18,0.10724
469.57,0.085607
518.96,0.061855

I've tried
df1 = pd.read_csv("df1.csv")
df2 = pd.read_csv("df2.csv", index_col=0).T
ax = df1.plot(marker="o")
df2.plot(x="T", y="zT", ax=ax, marker="o", label="base")

but that somehow produces false x-values for the first dataframe.

A: IIUC, I would try:
df1 = pd.read_csv("df1.csv", index_col='T')
# change column name to numbers
df1.columns = pd.to_numeric(df1.columns, errors='ignore')

df2 = pd.read_csv("df2.csv", index_col=0).T

# plot the transpose of df1
ax = df1.T.plot(marker="o")
df2.plot(x="T", y="zT", ax=ax, marker="o", label="base")

output:


text:
Q: Blackberry: creating a custom field to use with VerticalFieldManager to replicate tableview I don't know if I'm taking the correct route, but I've decided on making a custom field and using it within a verticalfieldmanager.
In the custom field I want to add an image on the left, and text on the right.
I've just started, but have run into some problems.
package mypackage;

import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

public class CustomEventField extends Field implements DrawStyle {

    private String title;
    private String by;
    private String date;
    private String desc;

    public CustomEventField(String title, String by, String date, String desc){
        super();
        this.title = title;
        this.by = by;
        this.date = date;
        this.desc = desc;

    }

    protected void layout(int width, int height) {
        setExtent(width,height);

    }

    protected void paint(Graphics graphics) {

        graphics.drawText(this.title, 0, 0);

        graphics.drawText(this.by, 50, 0);

    }

}

How do I have the drawText go to the next line from the drawText before it? Do I have to calculate the height of the font and add that to the y position?

A: According to above code it may not posible so I made one custom class which can display image , title ,date. when you click on item one dialog will display with its Index number
this is also useful for custom list view
Note: if you want try this following images available here you just use this PLease download sample images from here
If here any corrections please let me know
class CustomListField extends HorizontalFieldManager{

        private Bitmap scale_image;
        private int width=0;
        private int height=0;
        private int background_color=0;
        private BitmapField bitmap_field;
        private boolean flag=false;
        public CustomListField(String title, Bitmap image, String date,int image_width,int image_height,int background_color){
            super(NO_HORIZONTAL_SCROLL|USE_ALL_WIDTH);
            this.background_color=background_color;
            width=image_width;
            height=image_width;
            if(image!=null){
                scale_image=new Bitmap(image_width, image_height);
                image.scaleInto(scale_image, Bitmap.FILTER_LANCZOS);
                bitmap_field=new BitmapField(scale_image);
                flag=false;
                bitmap_field.setMargin(5, 5, 5, 5);
                add(bitmap_field);
            }

            VerticalFieldManager vmanager=new VerticalFieldManager(USE_ALL_WIDTH|Field.FIELD_VCENTER){
                protected void sublayout(int maxWidth, int maxHeight) {
                    super.sublayout(Display.getWidth()-width, height);
                    setExtent(Display.getWidth()-width, height);
                }
            };
            LabelField title_lbl=new LabelField("Title: "+title,Field.NON_FOCUSABLE|DrawStyle.ELLIPSIS);
            vmanager.add(title_lbl);

            LabelField date_lbl=new LabelField("Date: "+date,Field.NON_FOCUSABLE);
            vmanager.add(date_lbl);

            Font fon=title_lbl.getFont();
            int title_height=fon.getHeight();

            Font font=date_lbl.getFont();
            int date_height=font.getHeight();
            int pad=title_height+date_height;
            title_lbl.setPadding((height-pad)/2, 0, 0, 0);
            add(vmanager);
            add(new NullField(FOCUSABLE));
        }

        protected void sublayout(int maxWidth, int maxHeight) {
            super.sublayout(Display.getWidth(), height);
            setExtent(Display.getWidth(), height);
        }
        protected void paint(Graphics graphics) {
            if(flag)
            graphics.setBackgroundColor(background_color);
            graphics.clear();
            super.paint(graphics);
        }
        protected void onFocus(int direction) {
            super.onFocus(direction);
            flag=true;
            invalidate();
        }
        protected void onUnfocus() {
            invalidate();
            flag=false;
        }
        protected boolean navigationClick(int status, int time) {

            if(Touchscreen.isSupported()){
                return false;
            }else{
                fieldChangeNotify(1);
                return true;
            }

        }
        protected boolean touchEvent(TouchEvent message)
        {
            if (TouchEvent.CLICK == message.getEvent())
            {

                FieldChangeListener listener = getChangeListener();
                if (null != listener)
                    this.setFocus();
                    listener.fieldChanged(this, 1);
            }
            return super.touchEvent(message);
        }
    }

you can call this class as following way you have to pass Bitmap,title,image_height and width, and background clolor
      class sampleScreen extends MainScreen implements FieldChangeListener
        {
            private CustomListField cu_field[];
            private Bitmap image=null;
            int size=8;
            public sampleScreen() {
                VerticalFieldManager vmanager=new VerticalFieldManager(VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
                    protected void sublayout(int maxWidth, int maxHeight) {

                        super.sublayout(Display.getWidth(),Display.getHeight());
                        setExtent(Display.getWidth(),Display.getHeight());
                    }
                };
                cu_field=new CustomListField[size];
                for(int i=0;i<size;i++){
                    image=Bitmap.getBitmapResource("sample_"+i+".jpg");
cu_field[i]=new CustomListField("BlackBerry models that had a built-in mobile phone, were the first models that natively ran Java, and transmitted data over the normal 2G cellular network. RIM began to advertise these devices as email-capable mobile phones rather than as 2-way pagers.",
     image, "jan2011", 100, 100,Color.RED);
                    cu_field[i].setChangeListener(this);
                    vmanager.add(new SeparatorField());
                    vmanager.add(cu_field[i]);
                }
                add(vmanager);
            }

            public void fieldChanged(Field field, int context) {
                // TODO Auto-generated method stub
                for(int i=0;i<size;i++){
                    if(field==cu_field[i]){
                        final int k=i;
                        UiApplication.getUiApplication().invokeLater(new Runnable() {
                            public void run() {
                                Dialog.alert("You click on Item No "+k);
                            }
                        });
                    }
                }
            }
        }

Here you will get output as following image


text:
Q: Intent Filter of File Extension for specific activity I have 2 custom file extensions *.abc and *.xyz.
I have written Intent filters for activities where file having *.abc extension should be opened in Activity1 and *.xyz should be open in Activity2
Those files having serialized java objects and not plain text files.
These are intent filters for those activities in AndroidManifest.xml
<activity
    android:name=".ui.Activity1">
    <intent-filter tools:ignore="AppLinkUrlError">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />

        <data android:mimeType="*/*" />
        <data android:pathPattern=".*\\.abc" />
    </intent-filter>
</activity>
<activity
    android:name=".ui.Activity2">
    <intent-filter tools:ignore="AppLinkUrlError">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />

        <data android:mimeType="*/*" />
        <data android:pathPattern=".*\\.xyz" />
    </intent-filter>
</activity>

I am able to register those extension in android system and my app activities are showing in app chooser of Android System UI
I am printing URI info in logcat as follows
Timber.i(uri.toString())
val mimeType = contentResolver.getType(uri)
Timber.i(mimeType)

Logcat when file opened from WhatsApp
content://com.whatsapp.provider.media/item/5237
application/octet-stream

Logcat when file opened from Solid Explorer
content://pl.solidexplorer2.files/storage/emulated/0/Download/File1.abc
application/*

But when tap either of file (custom extension) it shows both Activities as openable Intent,
for eg. If click on file file1.abc it shows both Intent Filters of extensions as Activity1 and Activity2
I want to make those extensions Activity Specific
like if click on file with extension *.abc it should only have Activity1 in Intent Chooser of Android System UI
I have tried few methods explained in other answers but those doesn't seems to work properly for both file format with content type URI
Some solutions only working when file opened from File Browsers like Solid Explorer but doesn't work when open from apps like WhatsApp which uses MIME type as media
Intent filter below properly worked with Solid Explorer.
It is filtering activity based on custom file extension. But same Intent Filter won't work for Android System's Chooser dialog as it doesn't work in apps like WhatsApp or Gmail which uses Android System's Intent Chooser
<activity
    android:name=".ui.Activity1">
    <intent-filter>
        <data
            android:host="*"
            android:mimeType="*/*"
            android:pathPattern=".*\\.abc"
            android:scheme="content" />

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</activity>
<activity
    android:name=".ui.Activity2">
    <intent-filter>
        <data
            android:host="*"
            android:mimeType="*/*"
            android:pathPattern=".*\\.xyz"
            android:scheme="content" />

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</activity>

Any help will be appreciated.
Thanks.

A: There is no direct solution to this issue by using Intent Filters per Activity, So I have created FileIntentActivity which accepts following Intent Filter
<intent-filter
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    tools:ignore="AppLinkUrlError">
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.EDIT" />

    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="*/*" />
</intent-filter>

This FileIntentActivity is used to accept any file format and then decides further action based on file extension converted from Content URI using Cursors referred from this answer
fun getFileName(uri: Uri): String {
    lateinit var cursor: Cursor
    lateinit var result: String
    try {
        cursor = appContext.contentResolver.query(uri, null, null, null, null)
        if(cursor!=null && cursor.moveToFirst()){
            result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
        }
        return result
    } finally {
        cursor.close()
    }
}

private fun getFileType(fileName: String): FileType {
    return when (fileExtension) {
        FileFormats.ABC_FILE_FORMAT -> FileType.ABC
        FileFormats.XYZ_FILE_FORMAT -> FileType.XYZ
        else -> FileType.UNKNOWN
    }
}

And open the Activity1 or Activity2 based on FileType
private fun openActivityByType(fileType: FileType) {
    when (fileType) {
        FileType.ABC -> startActivity1()
        FileType.XYZ -> startActivity2()
        FileType.UNKNOWN -> showFileUnsupportedMessage()
    }
}

This approach at least makes User Interaction less confusing by showing only 1 File Intent Activity instead of Multiple Activities of Single app in Android's Intent Chooser.


text:
Q: Compile with Visual Studio Shell (Isolated) 2015 It is possible to use the compile command (cl and link) in Command Prompt if I only installed the VS Shell (isolated) which is part of the Atmel Studio?
Neither Command Prompt nor Power Shell know the cl command!
Edit :I searched for cl.exe and the developer promt but didn't found it.
Edit : downloaded visual studio tools but still can not find the developer promt :(
Unfortunately I can't install the full visual studio version.

A: If you have the Developer Command Prompt for VS 2015 installed, you can.
 Essentially, it's an application that opens a command prompt inside the directory C:\Program Files (x86)\Microsoft Visual Studio\2015\VERSION, where VERSION will depend on which edition of Visual Studio you have installed (Community, Professional, or Enterprise).
Otherwise you could cd into the folder where the compiler executable is and run it by typing its name, passing it parameters and pressing Enter, or you could add the path to it to your PATH environment variable (although I haven't tried this personally and can't vouch on how well this will work).


text:
Q: paging and sorting in grid view i have a code performing paging and sorting in grid view.
(bing_grid is user defined function)
public void bind_grid()
    {
        con = new SqlConnection();
        con.ConnectionString = "Data Source=STIRAPC105;InitialCatalog=anitha;Integrated Security=True";
        con.Open();

        SqlDataAdapter sqa = new SqlDataAdapter("select * from employees", con);
        DataSet ds = new DataSet();
        sqa.Fill(ds);
        DataTable mytab = ds.Tables[0];

        GridView1.DataSource = mytab;
        GridView1.DataBind();
        //con.Close();

    }

code for paging
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;

        bind_grid();

    }

code for sorting
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        DataTable dt = GridView1.DataSource as DataTable;
        if (dt != null)
        {
            DataView dataview = new DataView(dt);
            dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
            GridView1.DataSource = dataview;
            GridView1.DataBind();
        }
    }

user defined code for sorting
public string sort_grid()
    {
        string newSortDirection = String.Empty;

        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;

            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }

paging works, Errors was:
1. "no overload for method 'sort_grid' takes 1 argument" (dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);)

2.The name 'sortDirection does not exist in the current context. (switch (sortDirection))

Help me friends.

A: this method:
public string sort_grid()

takes no arguments but you are trying to call it with e.SortDirection:
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);

You must change the signature of sort_grid() to
sort_grid(SortDirection sortDirection)

This will also solve your second problem, which you are trying to use sortDirection variable, before declaring it in the method sort_grid.


text:
Q: Why can't I declare a variable name that consists of all digits? Why can't I declare a variable name that consists of all digits, e.g. my $123;?
I know that $1 is a special variable related to regexes. But $a is also a special variable (related to sort), and I can declare it in my code like this:
my $a;

Why can I do that but not
my $1;

or
my $123;

A: This is documented in the perldoc called perlvar.

Variable names in Perl can have several formats. Usually, they must begin with a letter or underscore, in which case they can be arbitrarily long (up to an internal limit of 251 characters) and may contain letters, digits, underscores, or the special sequence :: or '. [...]
Perl variable names may also be a sequence of digits or a single punctuation or control character. These names are all reserved for special uses by Perl; for example, the all-digits names are used to hold data captured by backreferences after a regular expression match. [...]

Taking this into account, these names are valid:
$a
$foo
$_
$_123
$_foo_bar_baz_
$_____

However, that doesn't mean it makes sense having them.
It's always a good idea to name a variable after what it contains. It is very hard to guess what a variable called $99 might contain. Maybe it's the 99th of something, in which case it should be an array index. Or it could be 99, in which case you could use a constant (99).


text:
Q: How to pass array from view to controller's action cakephp I'm fitering orders on basis of date, and I want to export the filtered orders, How to pass array from view to controller's action cakephp?
echo $this->Html->link(
    'Export Filtered Orders',
     array('action' => 'export_filtered', 'orders' => $orders),
     array('class' => 'btn btn-success')
);

A: You don't do that because it's against the MVC pattern and it won't work any way because this happens client side, you'll have to do a new request.
Alternativly use AJAX to update your view or implement the PRG pattern to refresh the page and apply the filters, see https://en.wikipedia.org/wiki/Post/Redirect/Get


text:
Q: High load and iowait on MySQL database server leads to slow MySQL INSERTS I have a MySQL database server runnuing on Ubuntu 12.10 with 64GB RAM, 2x3 TB SATA 6 Gb/s HDD 7200 rpm and software RAID 1 and an Intel Core i7-3930K.
The database server is accessed over a local network with a dedicated 1 GBit ethernet card.
The database is around 50 GB big and is the master in a replication setup.
IMO, there are two problems that lead to slow MySQL querying:

*

*The load is always relatively high (>2) even when the db server is idle (it's not a big problem since the processor has 12 cores but it doesn't seem right)

*top shows that around 95% of the system is idle, <1% is used 5% is waiting (see following screenshot)

iotop --only shows that most of the disk IO is produced by jdb2/md2-8 and not mysqld - so mysqld shouldn't be the problem - but why is jdb2/md2-8 using up so many ressources?
cat /proc/mdstat outputs the following:

My questions are:
What causes the slow MySQL performance?
Is it the iowait? What causes the iowait?
Is it the RAID 1 - Is it the used harddisk?
Any help is greatly appreciated!

A: You are running a log-heavy database on just about the slowest disks out there. The reason you're seeing jdb2 on such high iowaits is because it's having a hard time keeping up writing the ext4 journals to disk
Either change disks to something that can keep up (SSD's come to mind, allthough regular SAS disks with a battery cache would work) and/or start tuning stuff. There are plenty of documentation out there when it comes to filesystem tuning in SQL environments.
A good starting point is here: http://dev.mysql.com/doc/refman/5.0/en/disk-issues.html

A: I experienced this issue after upgrading to MySQL 5.7.
Setting "sync_binlog=0" fixed it for me. MySQL had changed the default from 0 to 1 in 5.7.


text:
Q: Website redirect, 301 redirection Live site- http://www.marchingmonk.com
When you click on the "home" button of the website, the user is not being redirected to http://www.marchingmonk.com, the user is redirected to http://www.marchingmonk.com/home, this creating a duplicate content issue.
Any idea how to fix that issue by making a 301 redirection

A: You fix by adding this to your htaccess file:
Redirect 301 /home /

And if you can, change the "home" link to just point to /.


text:
Q: Firebase web app - can't get user.uid when creating new account I am working on a small web app and I have hit a roadblock that I can't seem to overcome. I am able to register a new account, but I would like to save additional data to a database right after signing up.
This is what I have that I am confident that works fine.

$("#user-sign-up-button").click(function(){

  var firstName = $("#new-user-first-name").val();
  var secondName = $("#new-user-surname").val();
  var charity = $("#new-user-charity-account").val();
  var userEmail = $("#new-user-email").val();
  var userPassword = $("#new-user-password").val();
  var secondPassword = $("#new-user-repeated").val();

  firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword)

  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });

});

Now in regards to saving the additional variables to the database I have tried both of the below within .then part of createuserWithEmailAndPassword.

.then(
    function(user){
      var root = firebase.database().ref();
      var uid = user.uid;
      alert(uid);
      var postData = {  firstName: first_name,
        secondName: second_name,
        email: user_email,
        isCharity: charity };
        root.child("users").child(uid).set(postData);
    }

    function writeUserData(first_name, second_name, charity, user_email) {
      firebase.database().ref('users/' + user.uid).set({
        firstName: first_name,
        secondName: second_name,
        email: user_email,
        isCharity: charity
    });
  )

Both of the above solutions work within onAuthStateChanged but I want to capture the data at sign up, not every time someone signs in.
Any assistance would be great.

A: You must use .onAuthStateChanged to get at firebase.auth().currentUser. It's asynchronous and will be empty/null until it resolves. Also, don't forget that new email based accounts will not be .emailValidated:true until they have clicked a verification email link. ...something to consider.


text:
Q: Display data from dropdown in another div I have a dropdown with a list of values that are pulled from a MySQL database. Each of these values has other corresponding attributes in the database. This is the structure of that table:
id | name | password
The dropdown values are basically just all of the values in the "name" column.
What I'd like to do is display the id/name/password for a selected dropdown value in a separate div. That is, if I select "MIT" from the dropdown, I'd like the div to show me the id and the password associated with MIT. If I select "Harvard", I'd like the div to show the id and password associate with Harvard.
I am just looking for high-level suggestions on how I should approach a setup like this.
I was thinking of using AJAX and passing the selected value into a separate PHP file, which would then pull and display the associated ID and password. The div would then contain code to make a call to that PHP file and display the values on that page.
I think it'd work in theory, but it seems a bit cumbersome...any ideas for simplifying the process?

A: You could use data-attributes on your options. This would expose the passwords through the markup, but since they are accesible anyways through choosing the option in the dropdown, I guess this isn't an issue.
If you gave each option an attribute data-password="thepassword", then you could $("select").find(":selected").data("password") to retrieve the password. Do the same with a data-id attribute, and you're golden.
Another solution would be to have a JSon structure with the option values as keys. Let's say {"MIT":"1234","Harvard":"verysecret"} and then use $("select").change() and $(this).val() to retrieve the corresponding passwords (and other data) from you JSon structure.


text:
Q: TO_DATE error in Oracle When I run this query:
SELECT * FROM tbl_person
WHERE to_date(date_create, 'dd/mm/yyyy') < to_date('01/01/2010', 'dd/mm/yyyy')

I hit the following error:

ORA-01841: (full) year must be between -4713 and +9999, and not be 0

To be clear, date_create field stored SYSDATE when I added into table. What I need is to retrieve data from tbl_person table starting from 01/01/2010 onward.

A: You don't want to call TO_DATE on a DATE.  Just use the date column in the query (and compare it to a date)
SELECT *
  FROM tbl_person
 WHERE date_created < to_date('01/01/2010', 'dd/mm/yyyy')


text:
Q: Instantiate excel vba class i get "Compile Error Expected End of Statement '''
  Set SacarioSymbol= new obSacarioSymbol(SacarioGroupShapes)

No Mater what I try I can't get the compile error to clear.
Any help direction will be appreciated!


text:
Q: How to auto reload external code changes in Eclipse project ? I have started using Sublime text as my preferred code editor. But, I still rely on Eclipse for my maven build, server, and more.
Working on multiple editors could lead to another problem: whenever I make a change in some file outside of Eclipse, the IDE does not reload in the background. The files doesn't seem to sync, and I have to switch into Eclipse and make sure the changes are detected, then I can reload my page.
Doing 500 times of these in a day is annoying, does anybody have the same workflow and figure it out the solution for this, please let me know.
I am running on
Mac OS X 10.10 Yosemite
Eclipse Java EE IDE for Web Developers.
Version: Luna Service Release 2 (4.4.2)
Build id: 20150219-0600
Sublime Text 3
Feel free to suggest me anything.
Thanks.

A: Go to Window -> Preferences -> General -> Workspace and check Refresh on access. If that doesn't solve your problem check Refresh using hooks or polling also.


text:
Q: How access a value from another input inside focus-out function in ember 2? I need read a second value from a input and to do a search. So my component load a complementar info. Follow the form.
<form class="col-md-12 form-group">
   {{input type="text" classNames="form-control" placeholder="Place name" name="placeName" }}
   {{input type="text" class="form-control" placeholder="09111-620" name="zipcode" focus-out="searchPlace"}}
</form>

I need access placeName in focus-outaction. How I do this, after several search in google I don't see a solution using ember 2.

A: it is simple
{{input value=placeNameVal focus-out='placeNameFocusedOut'}}
{{input value=zipcodeVal focus-out='zipcodeFocusedOut'}}

in route or controller
actions: {
  zipcodeFocusedOut(zipcodeVal){
   console.log(zipcodeVal);
   console.log(this.get('placeNameVal')); // if you want to get other val
  },
  placeNameFocusedOut(placeNameVal) {
   console.log(placeNameVal);
   console.log(this.get('zipcodeVal')); // if you want to get other val
  }
}

A: I'm assuming that you want to be able to access whatever is currently in the Place Name field from within your zipcodeFocusedOut action.  To do this, you can bind the 'value' attribute of the text field as a property on your route or controller. In your template:
<form class="col-md-12 form-group">
   {{input type="text" classNames="form-control" value=placeNameValue placeholder="Place name" name="placeName" }}
   {{input type="text" class="form-control" placeholder="09111-620" name="zipcode" focus-out="searchPlace"}}
</form>

Instantiate that property as blank in your route or controller, and then you'll be able to refer to it in the action function:
in route or controller:
placeNameValue: '',

actions: {
  zipcodeFocusedOut(zipcodeVal){
   console.log(this.get('placeNameValue');
  }
}

Any time the text field value is changed, it will automatically change the associated placeNameValue field.  In other words, this.get('placeNameValue') will always represent the current value of that field, and you can access this anywhere within your controller/route.


text:
Q: session not working correctly in yii I am using sessions in when
 usercontroller
  actionlogin
             $userid=User::model()->fetch($username,$password);
            //  var_dump($userid);
             Yii::app()->SESSION['srid']=$userid;

in user model i have
 public function fetch($username,$password)
{

    $sql="select id FROM user where ( username='".$username. "' AND password='".$password."')";
    $connection=Yii::app()->db;
    $command=$connection->createCommand($sql);
    $resuserid=$command->queryAll();
    //var_dump($resuserid);
    $result=array();
    foreach($resuserid as $key=>$val)
    {$result[]=$val;}
    return $result;
    }

when i access this in some other controller
person personcontroller
i need to stored the
$model->personid=Yii::app()->SESSION['srid'];

the result of
var_dump($model->personid);

something
  array
0 =>
array
  'id' => string '24' (length=2)

the exact id is '24' but its appearing as string '24 '
error is
  personid must be a number.

the thing is session stores it as string but i need it as integer as personid is integer ..........
as well i want to know have we to configure session in config/main ...... do i need a db for it
Please help  i am losing my mind on this

A: From your code $result is an array not a string or int.
{$result[]=$val;}

should be
{$result=$val;}

Check out yii-user's implementation of UserIdentity for a better way to handle logins.

A: try this
public function fetch($username,$password)
{

    $sql="select id FROM user where ( username='".$username. "' AND password='".$password."')";
    $connection=Yii::app()->db;
    $command=$connection->createCommand($sql);
    // use queryColumn if you have to fetch only a single column
    $resuserid=$command->queryColumn();
    //var_dump($resuserid);
    $result=array();
    foreach($resuserid as $val)
    {
         // you can cast each value as integer like this
        $result=(int) $val;

    }
    return $result;
    }

Note:- Session stores the integers as integers only. The problem was that you were storing a it as the string.
If your query is going to return only a single value then you should use queryScalar().


text:
Q: leaf([X,[], []], [X]). how to get the list of leaves of a tree? I wrote this code for get the leaves of a tree.
    leaf([X,[], []], [X]).
    leaf([_, G, D], N) :-
       leaf(G, N1),
       leaf(D, N2),
       mix(N1, N2, N3),
       N is N3.

but when the this query is executed:
    ?- leaf([19, [18, [], []], [17, [], []]], N).

I get this error:
    ERROR: Type error: `[]' expected, found `[18,17]' (a list) ("x" must hold one character)
    ERROR: In:
    ERROR:    [9] _2656 is [18,17]
    ERROR:    [8] leaf([19,...|...],_2696) at e:/downloads/science/riag/university/1st master fond/1st semester/pp/tp/tp_prolog/tp1.pl:67
    ERROR:    [7] <user>

A: The problem is
N is N3.

You are using is as an assignement operator.
But it does the following:

*

*Evaluate the arithemtic expression on the right-hand-side

*Unify the result with the left-hand side

You don't need assignement at all.
Prolog provides logical variables which behave the same as references to global variables in stateful programming languages.
So, you just change whatever is named by the name N:
    leaf([X,[], []], [X]).
    leaf([_, G, D], N) :-
       leaf(G, N1),
       leaf(D, N2),
       mix(N1, N2, N). % UPDATE WHATEVER IS DESIGNATED BY N

The twist is that Prolog is assign-once:

*

*whatever is designated by N is a container (a memory cell)

*Initially this container is empty (aka. "the variable is uninstantiated" or "the variable is var", or var(N) succeeds).

*As the program proceeds the container is set to a term  (aka. "the variable is instantiated" or nonvar(N) succeeds). The term may be compley, i.e. a graph of (possibly filled) containers.

*You cannot unset the container's content except by making a previously done computation un-history, i.e. "by backtracking".

P.S.
`Type error: `[]' expected, found `[18,17]' (a list)

generated by SWI Prolog is really confusing. This may be due to the fact that one can write things like:
N is [a].

and N is unified with the (in SWI-Prolog, sanely Unicode) code point for a.
?- N is [a].
N = 97.

?- N is [97].
N = 97.

I think that was de mode to obtain (unwisely unspecified and unstandardized because EBCDIC is so hot in '95) codepoints in ancient Prologs. This should probably be burninated for good?
There is also the saner
?- N is 0'a.
N = 97.


text:
Q: Iterating through datagrid gives an error: "Unable to cast type" I have a datagrid which i populate using these codes:
public class items
{
    public string prfNo { get; set; }
    public string mrsNo { get; set; }
    public string itemName { get; set; }
    public string qty { get; set; }
    public string uom { get; set; }
    public string model { get; set; }
    public string brand { get; set; }
    public string remarks { get; set; }
    public string status { get; set; }
    public string purp { get; set; }
    public string approvedBy { get; set; }
    public string dateApproved { get; set; }
    public string preparedBy { get; set; }
    public string datePrepared { get; set; }
}

private void fillDatagrid()
    {
        if (chkNewItem.IsChecked == true)
        {
            purpose = "NEW ITEM";
        }
        else if (chkStock.IsChecked == true)
        {
            purpose = "STOCK";
        }
        else if (chkOthers.IsChecked == true)
        {
            purpose = txtOthers.Text;
        }

        ObservableCollection<items> itemData = new ObservableCollection<items>()
        {
            new items()
            {
                prfNo  = txtPRFNo.Text,
                mrsNo = txtMRSNo.Text,
                itemName = txtItem.Text,
                qty = txtQty.Text,
                uom = txtUOM.Text,
                model = txtModel.Text,
                brand = txtBrand.Text,
                remarks = txtRemarks.Text,
                status = txtStatus.Text,
                purp = purpose,
                approvedBy = txtApprovedBy.Text,
                dateApproved = txtApprovedDate.Text,
                preparedBy = txtPreparedBy.Text,
                datePrepared = txtPreparedDate.Text
            }
        };

        dgItems.ItemsSource = itemData;
    }

and i want to insert the data from datagrid to database table.
I tried iterating through datagrid using:
foreach (DataRowView dr in dgItems.ItemsSource)//ERROR HERE
{ }

but it gives me an error : "System.InvalidCastException: Unable to cast object of type 'items' to type 'System.Data.DataRowView'
What should I do?

A: Its because your ItemsSource contains collection of "items" and you have declared it as "DataRowView" in foreach loop.
Use it like this:
foreach (items dr in DataGrid1.ItemsSource) //ERROR HERE
{
}

OR
foreach (var dr in DataGrid1.ItemsSource) //ERROR HERE
{
}


text:
Q: using 50hz frequency in ac current Why we use exactly 50 Hz and 60 Hz, instead of 100 Hz or even 400 Hz
1-is it for light
2-is it for the speed of ac motors
Can I use a machine that work in 50 Hz ac network, in 60 Hz network

This picture shows a motor of 15 KW 220-230V /50HZ this motor run a water pumpe
My question is: can this motor work in 60 Hz network without damage
Will it's speed increase

A: Transformers - these would prefer both a lower frequency and a higher frequency. A lower frequency would mean eddy current losses in the laminates reduces. A higher frequency means fewer primary turns because primary inductive reactance increases and this means less copper loss under load.
So is 50 Hz the Goldilocks value for power transformers - no because other parts of the world use 60 Hz. Is 100 Hz too high - probably on the verge of being too high for power transformer cost effectiveness.
What about induced voltages from those overhead cables. The higher the frequency the greater the voltage induced in other objects and this in turn can cause problems. Faraday basically said this: -

So for a given current in an overhead conductor (for instance) the rate of change of flux would increase proportional to frequency and induced emf would increase in objects placed close by. Would this cause a problem at (say) 100 Hz. Maybe it would - maybe AC motors would suffer with increased losses in ironwork due to induced emfs causing eddy current flow. I guess this is pretty much related to laminate eddy currents in transformers.
Skin effect in conductors carrying high current is also of significant importance. Wiki shows a picture of overhead cable like this: -

Note the bundles of conductors formed into a triangle. Wiki say: -

The 3-wire bundles in this power transmission installation act as a
  single conductor. A single wire using the same amount of metal per
  kilometer would have higher losses due to the skin effect.

Increasing the frequency increases the skin effect and this will reduce the power delivery capability of feed cables because AC current tends to want to flow in the outer part of a conductor: -

How much will higher frequencies affect copper losses: -

So, if frequency doubles the AC resistance increases by \$\sqrt2\$.

A: The reasons to use 50 or 60Hz are mainly historical. Lower frequencies are problematic for lighting because of flicker.
Regarding your question, as others said, we have to know more about the specifics of your machine to answer. Some devices, for example electromechanical clocks, cannot work in frequencies different from those they were designed for.
https://en.m.wikipedia.org/wiki/Utility_frequency

A: 50/60 Hz is used to allow transfer over long distances. If you go to say 400 Hz, the power line inductance will become significant and you will need vast amount of compensation along a long transmission line. Transformer size would be smaller, but the overall cost would be much higher. For very long distances, you need to go even lower in frequency, i.e. HVDC, for sea cables (~500+ km) or very long overhead lines (10,000+ km)


text:
Q: How to programmatically add a background to a pdf? Given a .pdf file (produced by Inkscape with the LaTeX option, but I am more focused on the .pdf), is there a way to add programmatically a background (ideally, the background would be a rounded rectangle) to it? I am thinking typically of a python script or a C(or objective-C) library.
Typically:

I guess I should be easier to act directly (maybe via the command line) within Inkscape, but I am looking for a solution on the .pdf

A: If your background is also a PDF, you can use cpdf:
cpdf -stamp-under stamp.pdf input.pdf -o out.pdf

A: Working further from the answer of johnwhitington I found, that qpdf allows for that as well with the "underlay" option:
qpdf --underlay "background.pdf" -- input.pdf output.pdf

Great advantage: qpdf is available in most distributions. And as allways you can look at qpdf --help to find even more options to specify the page or to work inplace i.e. no need to specify an output file.
Ghostscript and Imagemagick allow for the same, but I found it quite hard to have a proper solution and the .pdf will become a rasterized image.


text:
Q: In my svg editor it is saying "Element style is missing required attribute type" I have the following svg but it's giving me a message saying "Element style is missing required attribute type".
Does anyone know how to fix this?
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 490.034 490.034">
    <defs>
    <style>.b{fill:#666666;}</style>
    </defs>
    <path class="b"     d="M435.667,54.311c-7-7.1-18.4-7-25.5,0l-64,64c-79.3-36-163.9-27.2-244.6,25.5c-60.1,39.2-96.6,88.5-98.1,90.6
        c-4.8,6.6-4.6,15.6,0.5,22c34.2,42,70,74.7,106.6,97.5l-56.3,56.3c-7,7-7,18.4,0,25.5c3.5,3.5,8.1,5.3,12.7,5.3s9.2-1.8,12.7-5.3
        l356-355.9C442.667,72.811,442.667,61.411,435.667,54.311z M200.467,264.011c-2.6-5.9-3.9-12.3-3.9-19c0-12.9,5-25.1,14.2-34.3
        c14.4-14.4,35.7-17.8,53.3-10.3L200.467,264.011z M290.667,173.911c-32.7-21-76.8-17.2-105.3,11.3c-16,16-24.7,37.2-24.7,59.7
        c0,16.4,4.7,32.1,13.4,45.6l-37.1,37.1c-32.5-18.8-64.5-46.6-95.6-82.9c13.3-15.6,41.4-45.7,79.9-70.8
        c66.6-43.4,132.9-52.8,197.5-28.1L290.667,173.911z"/>
    <path class="b" d="M486.067,233.611c-24.7-30.4-50.3-56-76.3-76.3c-7.9-6.1-19.2-4.7-25.4,3.1c-6.1,7.8-4.7,19.1,3.1,25.3
        c20.6,16.1,41.2,36.1,61.2,59.5c-11.8,13.8-34.8,38.6-66,61.3c-60.1,43.7-120.8,59.5-180.3,46.9c-9.7-2.1-19.3,4.2-21.3,13.9
        c-2.1,9.7,4.2,19.3,13.9,21.3c15.5,3.3,31.1,4.9,46.8,4.9c23.6,0,47.4-3.7,71.1-11.1c31.1-9.7,62-25.7,91.9-47.5
        c50.4-36.9,80.5-77.6,81.8-79.3C491.367,249.011,491.167,240.011,486.067,233.611z"/>
</svg>

A: Your <style> element requires a type attribute:
<style type="text/css">

More info here:  https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style


text:
Q: Draw a car draft ilustration in tikz I need to reproduce the following draw in tikz and I would appreciate some general instructions and tips on how to do it.

A: I am adding an answer, as I can't make a comment yet.
Check out https://www.sharelatex.com/blog/2013/08/27/tikz-series-pt1.html for the basics. One thing I'd suggest is using a grid, this really helps when you are making drawings as you can easily see your coordinate system. E.g.
\begin{tikzpicture}
\draw[step=5mm,very thin, color = gray](0mm,0mm)grid(100mm,100mm);
\end{tikzpicture}

After that its pretty simple! Have a play!


text:
Q: Yesod Persist create String key from JSON I have two pretty simple model definitions:
Page json
  uuid Text
  title Text
  UniquePageUuid uuid
  Primary uuid

Link
  uuid Text
  href Text
  pageId PageId Maybe
  Primary uuid

I would like to build a JSON endpoint to update the pageId in the Link model:
data ApiLink { linkPageId :: PageId } deriving (Generic)

instance FromJSON ApiLink

My handler would look something like this:
patchApiLinkR :: LinkId -> Handler Value
patchApiLinkR linkId = do
  jsonData <- requireJsonBody :: Handler ApiLink
  link <- runDB $ update linkId [LinkPageId =. (linkPageId jsonData)]
  returnJson link

Unfortunately I have no idea how to make this work, since the linkPageId in ApiLink has the type of PageId. I have seen some code to create DB Keys for Int64, but I don't know how to create them from Text values.
Thanks a lot!

A: You have to slightly change your db query to like this:
link <- runDB $ update linkId [LinkPageId =. (Just $ linkPageId jsonData)]