text:
Q: dynamic coloring of progress bar I have created a table with bootstrap progress styles, In which I am having a dynamic table which is having a column named Rank which contains several  values starts from 1 to 100 and by using jquery and bootstrap I have convert the values  into progress bar like as shown in the fiddle. Th code is working fine but the issue is with the color, currently It will show all in blue, actually I want different colors based on progress count values say 10 - yellow, 20 -blue, 35 - red etc, duplicates color should occur only for the same value, otherwise different color. color can be dynamic
My code is as given below
JSFiddle
$("#table").children("tbody").children("tr").each(function (i) {
    var col = $(this).children("td.value");
    console.log(col.html());
    var pro = '

 ' + col.html() + '
';
    col.html(pro);
});

Can anyone please tell me some solutions for this

A: Check this demo : http://jsfiddle.net/k1c9exLq/3/
Create an array of 100 items with different dynamic color codes first, then use them back based on your rank.
JQUERY
var genCol = [];
for (var i=0; i<=100; i++)
    genCol.push('#'+(Math.random()*0xFFFFFF<<0).toString(16));

$("#table").children("tbody").children("tr").each(function (i) {
    var col = $(this).children("td.value");

    var pro = '

 ' + col.html() + '
';

    col.html(pro);
});

A: Click Here
HTML

    Free Space

    Warning

    Danger

Bootstrap

A: You can use an if statement within your Jquery code.
if(col > 10)
{
 $('.progressbar').css('background', 'yellow');
}
And so on.


text:
Q: Custom Post type plugin is using theme single.php and style.css I am trying to make a plugin for the display of recipes on my website. I registered a custom post type which works. I even created a file called template-single.php for the elements I want to display in the post. The I call it with get_template_part() in single-af_recipe.php. For some reason this isn't working. My stylesheet for my plugin is also not working.
I tested this by putting the_title() in h4 tags. In the theme they are h1. I also made the h4 color red in af_style.css
Here are the files of my plugin:
I have a main file called recipe-maker.php where I include functions.php. Below I start from functions.php
functions.php
<?php

add_action('init', 'af_recipe_post_type');
add_action('wp_enqueue_scripts', 'af_enqueue_scripts');
register_activation_hook( __FILE__, 'af_pluginprefix_install' );

//Enqueue styles
function af_enqueue_scripts() {
    wp_enqueue_style('af_style', plugins_url( 'recipe-maker/af_style.css', dirname(__FILE__) ) );
}

function af_pluginprefix_install() {
    // clear the permalinks after the post type has been registered
    flush_rewrite_rules();
}

//Register custom post type for recipes
function af_recipe_post_type() {
    register_post_type('af_recipe',
        array(
            'labels' => array(
                'name' => __('Recipes'),
                'singular' => __('Recipe'),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array( 'slug' => 'recipe' ),
            'menu_icon' => 'dashicons-format-aside',
        )
    );

}

template-single.php
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<?php the_title(); ?>

<?php the_date(); ?>

    <?php the_content(); ?>

single-af_recipe.php

    <?php while ( have_posts()) : the_post(); ?>
        <?php get_template_part('template-parts/template-single.php'); ?>
    <?php endwhile; ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Service Broker : Multiple sources and one target... The connection was closed We try to setup a data replication with Service Broker. The topology is many sources sending data to one target.
Our solutions works with in one to one situation even when the faulty source is used...
When we use two sources, one a them (always the same) cannot be reach out and the reply is never sent... (the messages are correctly sent and receive by the target...)
The message in SQL Profiler is "The connection was closed by the remote end, or an error occurred while receiving data: '64(The specified network name is no longer available.)"
From the source point of view, the differences between our two sources are:

*

*the certificates, the sender services and the routes.

every other objets including queues, message types, contacts... are the same
Please let me know if you want the all SQL scripts

SSBdignose on server 1 :
Microsoft SQL Server 10.50.1600.1
Service Broker Diagnostic Utility
D  29925 LVICSV0003\DEV  DB_PMS_VILLAGE  Contract SBCTR_FLOW_ROWS does  not have the same definiton on the initiator and target
D  29974 LVICSV0002\DEV  DB_PMS_VILLAGE  The certificate CRT_PMS_SERVICE_BROKER_DIALOG_SOURCE_1 used by user USR_PMS_SERVICE_BROKER_DIALOG for dialog security is not deployed in the database.
D  29977 LVICSV0002\DEV  DB_PMS_VILLAGE  The user USR_PMS_SERVICE_BROKER_DIALOG from database DB_PMS_VILLAGE on LVICSV0003\DEV cannot be mapped into this database using certificates
D  29956 LVICSV0002\DEV                  The certificate used by server LVICSV0003\DEV for authentication is not deployed on server LVICSV0002\DEV. The Public role will be checked for CONNECT permission on the Service Broker endpoint on server LVICSV0002\DEV
D  29956 LVICSV0003\DEV                  The certificate used by server LVICSV0002\DEV for authentication is not deployed on server LVICSV0003\DEV. The Public role will be checked for CONNECT permission on the Service Broker endpoint on server LVICSV0003\DEV
3 Errors, 2 Warnings

SSB Diagnose on server 2 :
Microsoft SQL Server 10.50.1600.1
Service Broker Diagnostic Utility
D  29925 LVICSV0002\DEV  DB_PMS_VILLAGE  Contract SBCTR_FLOW_ROWS does  not have the same definiton on the initiator and target
D  29974 LVICSV0002\DEV  DB_PMS_VILLAGE  The certificate CRT_PMS_SERVICE_BROKER_DIALOG_SOURCE_1 used by user USR_PMS_SERVICE_BROKER_DIALOG for dialog security is not deployed in the database.
D  29977 LVICSV0002\DEV  DB_PMS_VILLAGE  The user USR_PMS_SERVICE_BROKER_DIALOG from database DB_PMS_VILLAGE on LVICSV0003\DEV cannot be mapped into this database using certificates
D  29956 LVICSV0003\DEV                  The certificate used by server LVICSV0002\DEV for authentication is not deployed on server LVICSV0003\DEV. The Public role will be checked for CONNECT permission on the Service Broker endpoint on server LVICSV0003\DEV
D  29956 LVICSV0002\DEV                  The certificate used by server LVICSV0003\DEV for authentication is not deployed on server LVICSV0002\DEV. The Public role will be checked for CONNECT permission on the Service Broker endpoint on server LVICSV0002\DEV
3 Errors, 2 Warnings


text:
Q: How to enable illegal characters in filenames on windows 10? I'm trying to create files with names such as: asterisk, pipe, uppercase letters and lowercase letters but Windows doesn't allow me for that. Is there command for enabling such feature? I'm using NTFS file system.
I tried using WSL and it didn't work, when I tried creating file using touch a.txt and touch A.txt and it didn't create second file named A.txt.

A: I don't think you can do it for at least these forbidden characters \ / : * ? " < > |. Window by default will not allow you to do that by any means.


text:
Q: Iniciar um vetor dentro de uma struct Boa tarde. Desejo iniciar um vetor de inteiros dentro de uma struct, porém ta acusando que necessita de um ";".

Segue a imagem. Obs: nao é a virgula dps do ultimo zero o problema, pois tirei a print antes de tirar, e mesmo dps de tirar continua com o mesmo problema.

A: Se n me engano, não é possível declarar o valor de uma variavel dentro de um struct. Vc vai ter que inicializar ela, algo assim:
 for(int i = 0; i < 32; i++){
     procedimento.dente[i] = 0;
 }


text:
Q: how to make the Lang selector working according to the value in local storage? hi I am working on this line of code, it's a language selector I was able to push the Lang selection to localstorage but how to make the page pick that stored value and stay on it ? after every refresh the page return back to the default English Lang, I ran out of ideas thanks.

Home

Art Gallary

Ria Art

Ria Projects

Videos

About

Contact

الصفحة الرئيسية

معرض اللوحات

فن الريا

مشاريع الريا

&nbsp فيديو &nbsp

 &nbsp عني &nbsp

تواصل معي

function langChange(selection) {

  document.body.setAttribute('lang', selection.value);

  storeLanguage(selection.value)
}

function storeLanguage(task) {

  let tasks;
  if (localStorage.getItem('tasks') === null) {
      tasks = [];
  } else {
      tasks = JSON.parse(localStorage.getItem('tasks'))
  }

  tasks.push(task)

  localStorage.setItem('tasks', JSON.stringify(tasks));
}

A: as explained on the How to change a :lang selector style with JavaScript page
here is the same code (modernized) and completed with the memorization of the chosen language in localStorage
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title> xyz </title>

  <select id="language-selector">
    <option value="en" selected > English language </option>
    <option value="ar"          > اللغة العربية    </option>
  </select>

 Home

 Art Gallary

 Ria Art

 Ria Projects

 Videos

 About

 Contact

 الصفحة الرئيسية

 معرض اللوحات

 فن الريا

 مشاريع الريا

   فيديو

   عني

 تواصل معي


text:
Q: Error change favicon magento 1.9.3.7 I want change favicon in multistore configuration:
System > Config > General > Design > HTML Head > Favicon Icon
but when i try to use filetype .ico i receive: Invalid image.
and in tips: Allowed file types: ICO, PNG, GIF, JPG, JPEG, APNG.
And I think it's work in early version because i have custom favicon.ico in other store in this site.

A: *

*Check if your favicon.ico image is well saved as .ico otherwise there are several online tools to convert the image to ico format, try this first.

*Check the _getAllowedExtensions() function content bellow if it is present with the right content in : app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Image/Favicon.php
/**
 * Getter for allowed extensions of uploaded files.
 *
 * @return array
 */
protected function _getAllowedExtensions()
{
    return array('ico', 'png', 'gif', 'jpg', 'jpeg', 'apng');
}


text:
Q: Codeigniter base url issue with www I have declared the base url as $config['base_url'] = 'http://example.com/';.
But the issue is if someone try to access my website with  'http://www.example.com/'; , css/ js functions are not working.
If I change the base url to 'http://www.example.com/' , users cannot access with 'http://example.com/'.
I am using codeigniter 3.0.3 . This is an issue with a website which is already online.
CSS - assets/plugins/bootstrap/css/bootstrap.min.css" />
JS - ">
. btw , ajax request are also failed.When I try to access an ajax function the bellow error showing on console –
XMLHttpRequest cannot load http://www.example.com/Dynamic/home/normal/4. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.
css error
Font from origin 'http://www.example.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.

A: I think the following code-block shows the best way to configure the base_url in Codeigniter :
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

And I strongly believe that this will solve your problem. Thank you.

A: Change your base url from
$config['base_url'] = 'http://example.com/';
to
$config['base_url'] = 'http://www.example.com/';
Reason:www and non-www website url are considered as different website so it gives the error of

Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin'

Better way is the add code in htaccess to convert non-www to www.
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www\.%{HTTP_HOST}/$1 [L,R=301]

Hope this explain the reason of change...

A: Define baseUrl like this
$config['base_url'] = 'stackoverflow.com/';

and .htaccess should be
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

As well as make sure URL helper is loaded.


text:
Q: What's the "right" way to override a symfony extension from another bundle I need to override the file
/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Extension/AssetsExtension.php
It loads the twig getAssetUrl from the bundle using the twig function 'asset'
/**
 * Returns a list of functions to add to the existing list.
 *
 * @return array An array of functions
 */
public function getFunctions()
{
    return array(
        new \Twig_SimpleFunction('asset', array($this, 'getAssetUrl')),
        new \Twig_SimpleFunction('assets_version', array($this, 'getAssetsVersion')),
    );
}

I want to override the asset() twig function without touching the core files, which otherwise would be overridden by the next symfony update

A: Consider that your code live in AppBundle namespace. First create service configuration in app/config.yml or src/AppBundle/Resources/config/something.yml (you have to load this configuration file in bundle extension). Don't forget place it under services key.
twig.extension.assets:
    class:     AppBundle\Twig\AssetsExtension
    arguments: ["@service_container", "@?router.request_context"]
    public: false
    tags:
        - { name: twig.extension }

Now let's create extension src/AppBundle/Twig/AssetsExtension.php. This class inherits from original extension and I will override just one method (in template asset()).
<?php

namespace AppBundle\Twig;

class AssetsExtension extends \Symfony\Bundle\TwigBundle\Extension\AssetsExtension
{
    public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null)
    {
        return parent::getAssetUrl('/something/' . $path, $packageName, $absolute, $version);
    }
}

Now, after reload, all your assets should be incorrect and prefixed with /something/ by default. You can try to delete Symfony cache in case of problems. I tested this scenario on Symfony 2.5.5.
Another way how to work with built-in services is compiler pass. In compiler pass you can modified whole Symfony service container (delete, replace, modify services). Symfony is all about DIC. I hope it is good enough solution.

A: I provide another solution, because since symfony 3.0 the services' class names are not overridable anymore.
You have to chose the compiler pass solution.
Let's say you want to override url() function in twig, you should create a compiler pass for it and change the definition :
<?php
// AppBundle/AppBundle.php

namespace AppBundle;

use AppBundle\DependencyInjection\Compiler\TwigRoutingExtensionPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new TwigRoutingExtensionPass());
    }
}

Then create the TwigRoutingExtensionPass file :
<?php
// AppBundle/DependencyInjectoin/Compiler/TwigRoutingExtensionPass.php

namespace AppBundle\DependencyInjection\Compiler;

use AppBundle\Twig\Extension\RoutingExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class TwigRoutingExtensionPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (false === $container->hasDefinition('twig.extension.routing')) {
            return;
        }

        $definition = $container->getDefinition('twig.extension.routing');
        $definition->setClass(RoutingExtension::class);
    }
}

And then create your RoutingExtension file.
If you want to inject some services to the new extension :
<?php

    $definition->addArgument('some_service');
    // OR
    $definition->addMethodCall('setSomeService' [$container->get('some_service')]);

A: You might also want to have a look at Symfony's "decorate"
# If it is a named service
My\CoreBundle\Twig\OverrideItWithThisExtension:
    decorates: 'some.other.twig_extension'

# If the service has a "FQCN"
My\CoreBundle\Twig\OverrideItWithThisExtension:
    decorates: Some\Other\TwigExtension

This way the original service actually still exists and you can still access it if you really want


text:
Q: retrofit2 get json object without jsonArray name I want to take jsonobject using retrofit without class definition, the result is null. How about this ?
I have a get query with JSON response :
[{"Kuota":"12"}]

This my code get data JSONObject .
public void GetKuota(String Key) {
    IBookingService iBookingService = APIClient.getClient().create(IBookingService.class);
    Call<ResponseBody> call = iBookingService.getKuota(Key);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(!response.isSuccessful()) {
                JSONObject jsonObject;
                try {

                    jsonObject = new JSONObject(response.body().toString());
                     // Log.d(jsonObject.getString("Kuota"));
                     datas =String.valueOf(jsonObject.getInt("Kuota"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

        }
    });

}

A: Suggestion:
Create a model class, lets say Kuota
public class Kuota {
   public int Kuota;
}

Then rewrite the Retrofit callback like this.
iBookingService.getKuota(Key).enqueue(new Callback<List<Kuota>>() {
    @Override
    public void onResponse(Call<List<Kuota>> call, Response<List<Kuota>> response) {
        if(response.code() == 200 && response.body() != null) {
              try {

                for(Kuota k: response.body()) {
                    Log.d("Kuota Value" , " " + k.kuota);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call<List<Kuota>> call, Throwable t) {

    }
});

Replace iBookingService data holder from ResponseBody to List< Kuota >
if not added, please add the JSON serializer while setting up Retrofit instance.
      new Retrofit.Builder()
            .......
            .addConverterFactory(GsonConverterFactory.create())
            .build();

And also add the dependency
  implementation 'com.squareup.retrofit2:converter-gson:2.4.0'


text:
Q: How do I get the name from a named tuple in python? I create a named tuple like this:
from collections import namedtuple
spam = namedtuple('eggs', 'x, y, z')
ham = spam(1,2,3)

Then I can access elements of ham with e.g.
>>> ham.x
1
>>> ham.z
3

In the interpreter,
>>> ham
eggs(x=1, y=2, z=3)

But what if I just want to get 'eggs'? The only way I've been able to think of is
>>> ham.__repr__.split('(')[0]
'eggs'

but this seems a bit messy. Is there a cleaner way of doing it?
Why do named tuples have this 'eggs' aspect to them if it isn't possible to access it without resorting to a private method?

A: You can get the __name__ attribute of the class:
>>> type(ham).__name__
'eggs'

(Here using the type() builtin to get the class).

A: On the topic of namedtuple attributes:
 >>> ham._fields
    ('x', 'y', 'z')

is sometimes useful to know

A: Based on python's doc, namedtuple gives you a new tuple subclass named 'eggs'
So essentially you need the class name
and type(ham).__name__ will give you the class name

A: >>> ham.__class__.__name__
'eggs'


text:
Q: Is there a way to sum values to the right of a + symbol across many cells? I am normally well versed in Excel but I am having a blank on this one.
I have a bunch of formulas eg:
VLOOKUP($C22, 'Pivot Table'!$A$4:$DD$400, 13, FALSE)+3162
VLOOKUP($C22, 'Pivot Table'!$A$4:$DD$400, 22, FALSE)+18
VLOOKUP($C22, 'Pivot Table'!$A$4:$DD$400, 31, FALSE)
VLOOKUP($C22, 'Pivot Table'!$A$4:$DD$400, 40, FALSE)+8.6

and so on
What I need is a formula that will sum all numbers to the right of the +, trying to avoid using VBA (which would be super easy) for reasons beyond my control.

A: If you are using Excel 2013 you can use FORMULATEXT function to get the formula as text, then extract the number, e.g. with formulas in A2 down use this formula in B2 copied down
=IFERROR(LOOKUP(10^9,RIGHT(FORMULATEXT(A2),{1,2,3,4,5,6,7,8,9})+0),0)
That will extract numbers from the right of the text (up to 8 digits, excluding sign). It will give you negative, positive or zero if there is no number at the right of the formula.
Clearly you can sum column B for the total

A: Nowhere as neat as @barry (of course!) but an alternative that works for you examples is to copy the formulae and on the copy Find what *), Replace with: (nothing) and sum the results.


text:
Q: Whats the best way to store different prices for one entity in SQL? So I am building a webpage that shows a bunch of video games located in a SQL database and one suggestion I had was to have the different prices from each region display based on a drop down. My question is trying to figure out whats the best way to store int in the database. Would it be like:

*

*GAME

*

*CountryID

*price1

*CountryID

*price2

*CountryID

*price3 ...

Or is there a better way to do this?
Just a heads up I've only been developing web applications for a year or so and I'm still pretty new to SQL.
Thanks for your input!

A: I would use multiple tables, one for games and one for region pricing.
Games
+--------+----------+
| GameID | GameName |
+--------+----------+
|      1 | Game1    |
|      2 | Game2    |
|      3 | Game3    |
|      4 | Game4    |
+--------+----------+

RegionPricing
+----------+--------+-------+
| RegionID | GameID | Price |
+----------+--------+-------+
|        1 |      1 |    60 |
|        1 |      2 |    55 |
|        1 |      3 |    45 |
|        1 |      4 |    80 |
|        2 |      1 |    50 |
|        3 |      2 |    30 |
|        3 |      3 |    25 |
|        3 |      4 |    45 |
|        4 |      1 |    60 |
|        4 |      2 |    55 |
|        4 |      3 |    45 |
|        4 |      4 |    80 |
+----------+--------+-------+

By using separate tables you minimize duplicate data and allow for easy granular changes. You may also consider adding a column to RegionPricing for currency. This would also need a Region table, with RegionID and RegionName.


text:
Q: How to navigate to sections(divs) on one web page? It's a one page navigation with three sections. The navigation wont go the divs , it doesn't do anything. What am I doing wrong?
I wasn't sure if I need to add JS? The divs are there and are working properly but the navigation won't navigate to those sections...

About

Portfolio

Contact

A: 1) the href must point to the id of another element. if you have  you must have an element with an id attribute of id='somelink'.
2) id's must be unique. you cannot have more than one element with the same id. all of your links have the same  id.

A:

About

Portfolio

Contact


text:
Q: Create attribute in PHP by selecting tag name I am trying to load html, find a tag and add an attribute to it, before showing it.
I have tried:
libxml_use_internal_errors(true);

$domDocument->loadHTML("Test
");
$domElement = $domDocument->getElementsByTagName('body');

foreach ($domElement as $formula) {
    $formula->nodeValue->createAttribute('name')->value = 'attributevalue';
}

libxml_use_internal_errors(false);

But I have this error:

Call to a member function createAttribute() on string

Do you have a solution please ?
Best regards

A: The nodeValue returns the String type, which isn't the way to create an attribute.
And in fact, the node's type is DOMElement, so you need to set the attribute as similar as the following code:
<?php
$domDocument = new DOMDocument();
$domDocument->loadHTML("Test
");
$domElement = $domDocument->getElementsByTagName('body');
foreach ($domElement as $formula) {
    $formula->setAttribute("name", "attributevalue");
}
?>

A: Try it like this
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML("Test
");
$domElements = $doc->getElementsByTagName('body');
foreach ($domElements as $domElement) {
    $domAttribute = $doc->createAttribute('name');
    $domAttribute->value = 'attributevalue';
    $domElement->appendChild($domAttribute);
    print_r($domElement->getAttribute('name'));
    // returns attributevalue
}
libxml_use_internal_errors(false);

Try it out @PHP-Sandbox

A: Here is a possible solution where setAttribute is used instead of create. Though I am not sure the purpose of the loop since there is usually only 1 body tag.
libxml_use_internal_errors(true);

$domDocument->loadHTML("Test
");
$domElement = $domDocument->getElementsByTagName('body');

foreach ($domElement as $formula) {
    $formula->setAttribute('name', 'thevalue');
}

libxml_use_internal_errors(false);


text:
Q: Rails model association problem I'm new at active record association in rails so i don't know how to solve the following problem:
I have a tables called 'meetings' and 'users'. I have correctly associated these two together by making a table 'participants' and set the following association statements:
class Meeting < ActiveRecord::Base
    has_many :participants, :dependent => :destroy
    has_many :users, :through => :participants

and
class Participant < ActiveRecord::Base
    belongs_to :meeting
    belongs_to :user

and the last model
class User < ActiveRecord::Base
    has_many :participants, :dependent => :destroy

At this point all is going well and i can access the user values of attending participants of a specific meeting by calling @meeting.users in the normal meeting>show.html.erb view.
Now i want to make connections between these participants. Therefore i made a model called 'connections' and created the columns of 'meeting_id', 'user_id' and 'connected_user_id'. So these connections are kinda like friendships within a certain meeting.
My question is: How can i set the model associations so i can easily control these connections?
I would like to see a solution where i could use
@meeting.users.each do |user|
    user.connections.each do |c|
        <do something>
    end
end

I tried this by changing the model of meetings to this:
class Meeting < ActiveRecord::Base
    has_many :participants, :dependent => :destroy
    has_many :users, :through => :participants
    has_many :connections, :dependent => :destroy
    has_many :participating_user_connections, :through => :connections, :source => :user

Please, does anyone have a solution/tip how to solve this the rails way?

A: My understanding of your problem is that you want to make a connection between users who attended the same meeting.Maybe this will work.
In the Participant model
 has_many => :connections
 has_many => :users, :through => :connections

In the User model
has_many => :connections

Then I suppose you can do :
@meeting.users.each do |user|
    user.connections.each do |c|
        #access each user object through the object |c|
    end
end

A: I had a wrong understanding on how the associations in Models work. Because of this wrong view my question was wrong to begin with.
For example I have a model meetings Meetings which has many Participants from the model Participants. I didn't knew that I cannot only retrieve the meeting.participants, but that i can also access the meeting that the participant is assigned to with participant.meeting.
So i just simply changed the columns user_id and connected_user_id of table participant to participant_id and connected_participant_id. Then in the models i did.
Model Participant:
class Participant < ActiveRecord::Base
    belongs_to :meeting
    belongs_to :user
    belongs_to :participating_user, :class_name => 'User', :foreign_key =>'user_id'
    has_many :connections

Model Connection:
class Connection < ActiveRecord::Base
    belongs_to :participant, :foreign_key => 'connected_participant_id'

With these associations i could simply access the connections of the corresponding participant in the view by using:
View (haml code)
- @meeting.participants.each do |p|
    %p
        %b Participant:
        = "#{p.user.first_name} #{p.user.last_name}"
    - p.connections.each do |c|
        %p
        %b Participant:
        = "#{c.participant.user.first_name} #{c.participant.user.last_name}"

One last thing, these nested resources of c.participant.user.firstname is very long. I rather like to see something like p.connected_participants that would address the Participant model.
Does anyone know how to shorten these nested resources?


text:
Q: ICSharpCode.SharpZipLib.Zip example with crc variable details I am using icsharpziplib dll for zipping sharepoint files using c# in asp.net
When i open the output.zip file, it is showing "zip file is either corrupted or damaged".
And the crc value for files in the output.zip is showing as 000000.

*

*How do we calculate or configure crc value using icsharpziplib dll?

*Can any one have the good example how to do zipping using memorystreams?

A: it seems you're not creating each ZipEntry.
Here's is a code that I adapted to my needs:
http://wiki.sharpdevelop.net/SharpZipLib-Zip-Samples.ashx#Create_a_Zip_fromto_a_memory_stream_or_byte_array_1
Anyway with SharpZipLib there are many ways you can work with zip file: the ZipFile class, the ZipOutputStream and the FastZip.
I'm using the ZipOutputStream to create an in-memory ZIP file, adding in-memory streams to it and finally flushing to disk, and it's working quite good. Why ZipOutputStream? Because it's the only choice available if you want to specify a compression level and use Streams.
Good luck :)

A: 1:
You could do it manually but the ICSharpCode library will take care of it for you.  Also something I've discovered: 'zip file is either corrupted or damaged' can also be a result of not adding your zip entry name correctly (such as an entry that sits in a chain of subfolders).
2:
I solved this problem by creating a compressionHelper utility.  I had to dynamically compose and return zip files.  Temp files were not an option as the process was to be run by a webservice.
The trick with this was a BeginZip(), AddEntry() and EndZip() methods (because I made it into a utility to be invoked. You could just use the code directly if need be).
Something I've excluded from the example are checks for initialization (like calling EndZip() first by mistake) and proper disposal code (best to implement IDisposable and close your zipfileStream and your memoryStream if applicable).
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

public void BeginZipUpdate()
    {
        _memoryStream = new MemoryStream(200);
        _zipOutputStream = new ZipOutputStream(_memoryStream);
    }

public void EndZipUpdate()
    {
        _zipOutputStream.Finish();
        _zipOutputStream.Close();
        _zipOutputStream = null;
    }

//Entry name could be 'somefile.txt' or 'Assemblies\MyAssembly.dll' to indicate a folder.
//Unsure where you'd be getting your file, I'm reading the data from the database.
public void AddEntry(string entryName, byte[] bytes)
    {
        ZipEntry entry = new ZipEntry(entryName);
        entry.DateTime = DateTime.Now;
        entry.Size = bytes.Length;
        _zipOutputStream.PutNextEntry(entry);
        _zipOutputStream.Write(bytes, 0, bytes.Length);
        _zipOutputStreamEntries.Add(entryName);
    }

So you're actually having the zipOutputStream write to a memoryStream. Then once _zipOutputStream is closed, you can return the contents of the memoryStream.
public byte[] GetResultingZipFile()
    {
        _zipOutputStream.Finish();
        _zipOutputStream.Close();
        _zipOutputStream = null;
        return _memoryStream.ToArray();
    }

Just be aware of how much you want to add to a zipfile (delay in process/IO/timeouts etc).


text:
Q: Return a growing number based on another number in javascript I want to make a function taking one number argument that returns:

*

*4 for 0.1

*8 for 1

*etc... it should return a valid number following that pattern no matter what number is passed, though the number is typically expected to be a float between 0 and 1
I don't know the proper term to call this kind of operation.
I can only come up with a function like num => 4 + 4 * num, but that is incorrect since passing 0.1 returns 4.4.

A: You could take the logarithm of ten and some adjustments.

const f = x => x && 8 / (1 - Math.log10(x));

console.log(f(0.001)); // 2
console.log(f(0.1));   // 4
console.log(f(1));     // 8

Or slightly different

const f = x => x && 8 / (1 + Math.log10(1 / x));

console.log(f(0.001)); // 2
console.log(f(0.1));   // 4
console.log(f(1));     // 8


text:
Q: How to get temporary persistent credentials accessing google applications by Java Code I'm on practice with google drive/sheets/oauth API Java for a standalone application.
My focus is now on client authentication.
I registered my application on google developer console and got the client json file.
So, following the tutorial, this is the Authentication snippet of code
/** Directory to store user credentials for this application. */

private static final java.io.File DATA_STORE_DIR = ResourceLoader.googleCredentials();

/** Global instance of the {@link FileDataStoreFactory}. */
private static DataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/drive-java-quickstart
 */
private static final List<String> SCOPES =
    Arrays.asList(DriveScopes.DRIVE);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    } catch (Throwable t) {
        MyLogger.getLogger().severe(t);
    }
}

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
private Credential authorize() throws IOException {
    // Load client secrets.
    //InputStream in = GDriveQuickStart.class.getResourceAsStream("/client_secret.json");

    Credential credential = null;

        InputStream in = new FileInputStream(ResourceWorking.googleClientSecretPath());

        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        MyLogger.getLogger().info(clientSecrets.getDetails().toPrettyString());

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(DATA_STORE_FACTORY)
                .setAccessType("offline")
                .build();
        credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");

        MyLogger.getLogger().info(credential.getAccessToken()+" "+credential.getRefreshToken()+" "+credential.getExpirationTimeMilliseconds()+" "+credential.getExpiresInSeconds());

    return credential;
}

When the application runs for the first time, it opens a browser page for the authentication by google user and acceptance of terms of condition.
Then, the credentials are saved into the folder identified by `DATA_STORE_DIR (tipically .credentials/StoredCredential binary file).
In this way, running again the application avoid the browser page opening: you are always authenticated.
So, I would that this Stored Credentials had an expiration time and so, after, for example, one month, the browser page opens again and the Stored Credential will be overrided.
Check the last log line: the access token has a life of only one hour but when it expires it refresh automatically.
The only way I've found is using the MemoryDataStoreFactory instead of FileDataStoreFactory but in this way every time the application runs it opens the browser page.
So, is there a way by Google API to obtain temporary Stored Credential?
I explain why I want it: the application will be used by different users. I want to avoid the critical case that would happen whent a user copies the application folder and give it to another user. The credential folder is into the application folder and so he will copy the StoredCredential file too. The new user so will use the application with the old user authentication.

A:
I explain why I want it: the application will be used by different users. I want to avoid the critical case that would happen whent a user copies the application folder and give it to another user. The credential folder is into the application folder and so he will copy the StoredCredential file too. The new user so will use the application with the old user authentication.

This is actually very important you dont want to take the chance of leaking user information.  However you also need to consider that you cant protect yourself from everything stupid users will do.
The .Net Client Library defaults FileDataStore saving to %appdata% for this very reason.   The Java client library and the .net Client libraries are designed quite similar thats how i can help a bit with this.
What you need to do is just store your credentials out side your main application folder I am not sure what system you are running on but %appdata% works well for windows.  THis way if the user does copy the directory they wont by chance copy your credeintals files.
Another option would be to make your own implementation of the data store and maybe add some kind of check so that when they are created use the mac address of the machine and only load them if its the same machine.   This is a bit over kill if you ask me.


text:
Q: Splitting string values with more than 4 values in sql query in SQL server 16 I want to split string "val=ABC_DEF_GHI_JKL_MNO_PQR" in to different column values and Parsename function is not accepting split criteria with more than 4 splits.
This values are coming from Table and needed to implement the function using  SQL fucntions if possible.
PARSENAME(replace(val,'_','.'),4) as col1 and returning null. How can i split this value?

A: For SQL Server 2016 I have implemented two query below. Query#1 will split the string into rows with string_split() function. Query#2 will split the string into columns with string_split() and dynamic pivot technique.
Create table and insert statements:
 create table testtable (teststring varchar(50));
 insert into testtable values('ABC_DEF_GHI_JKL_MNO_PQR');

Query#1
 select  row_number()over(order by (select null)) rn, [value] as Street1 from testtable
    cross apply string_split(teststring,'_')

rn
Street1

1
ABC

2
DEF

3
GHI

4
JKL

5
MNO

6
PQR

Or without row number it's just :
select   [value] as Street1 from testtable
   cross apply string_split(teststring,'_')

Query#2:
 DECLARE @cols  AS NVARCHAR(MAX)='';
 DECLARE @query AS NVARCHAR(MAX)='';

 with cte as
 (
  select  row_number()over(order by (select null)) rn, [value] as Street1 from testtable
  cross apply string_split(teststring,'_')
 )
 select  @cols = STUFF((SELECT distinct ',' + quotename(rn)
             FROM cte
             FOR XML PATH(''), TYPE
             ).value('.', 'NVARCHAR(MAX)')
         ,1,1,'')

 set @query = 'SELECT  ' + @cols + ' from
 (
    select  row_number()over(order by (select null)) rn, [value] as Street1 from testtable
    cross apply string_split(teststring,''_'')
 ) src
 pivot
 (
     max(street1) for rn in (' + @cols + ')
 ) piv'

 execute(@query)

Output:

1
2
3
4
5
6

ABC
DEF
GHI
JKL
MNO
PQR

db<>fiddle here
If you are using MySQL 8.0 then with recursive common table expression you can easily split this to rows :
 create table testtable (teststring varchar(50));
 insert into testtable values('ABC_DEF_GHI_JKL_MNO_PQR');

Query:
 with RECURSIVE cte (street1,level)as
 (
 select SUBSTRING_INDEX(teststring, '_', 1) AS street1, 1 as level
 from testtable

 union all

 select SUBSTRING_INDEX(SUBSTRING_INDEX(teststring, "_", level+1), "_", -1),level+1
 from cte inner join testtable t
 on cte.street1<SUBSTRING_INDEX(SUBSTRING_INDEX(teststring, "_", level+1), "_", -1)
 )
 select street1 from cte

Outupt:

street1

ABC

DEF

GHI

JKL

MNO

PQR

db<fiddle here

A: SUBSTRING_INDEX is your goal.
set @val="ABC_DEF_GHI_JKL_MNO_PQR" ;

select
    SUBSTRING_INDEX(@val, "_", 1) as no1,
    SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 2), "_", -1) as no2,
    SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 3), "_", -1) as no3,
    SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 4), "_", -1) as no4,
    SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 5), "_", -1) as no5,
    SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 6), "_", -1) as no6;

sample
MariaDB [bernd]> select @val;
+-------------------------+
| @val                    |
+-------------------------+
| ABC_DEF_GHI_JKL_MNO_PQR |
+-------------------------+
1 row in set (0.01 sec)

MariaDB [bernd]>
MariaDB [bernd]>
MariaDB [bernd]> select
    -> SUBSTRING_INDEX(@val, "_", 1) as no1,
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 2), "_", -1)as no2,
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 3), "_", -1)as no3,
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 4), "_", -1)as no4,
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 5), "_", -1)as no5,
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(@val, "_", 6), "_", -1)as no6;
+------+------+------+------+------+------+
| no1  | no2  | no3  | no4  | no5  | no6  |
+------+------+------+------+------+------+
| ABC  | DEF  | GHI  | JKL  | MNO  | PQR  |
+------+------+------+------+------+------+
1 row in set (0.01 sec)

MariaDB [bernd]>


text:
Q: Add new image block, set default class name and update it using Javascript I am trying to programmatically set a default class on an image block, which is applied without the user manually adding it via the 'Additional CSS' field.
I have tried applying a default style on image blocks, which works initially -
wp.blocks.registerBlockStyle( 'core/image', {
  name: 'retailResidential',
  label: 'Retail & Residential',
  isDefault: true
});

But after it is initialized, unregistering the block style, then registering a new default block style has no effect for additionally created images (does not create an image with the updated default style, still uses the old).
wp.blocks.unregisterBlockStyle(
  'core/image',
  [ 'retailResidential', 'weddingsEvents', 'advertisingEditorial']
);

Does the editor need to be refreshed? or is there a better way of doing this?


text:
Q: Magento 2 decode widget code in category description I have added widget(call static block) in category description http://prntscr.com/ko816y.But it is not call widget in front just showing output as it look in admin WYSIWYG editor.
So,I want to convert below code to html
{{widget type="Magento\Cms\Block\Widget\Block" template="widget/static_block/default.phtml" block_id="10"}}

How can I convert widget code to html?
EDIT
I have Call Description like this way
<?= /* @escapeNotVerified */ $this->helper('Magento\Catalog\Helper\Output')->categoryAttribute($block->getCurrentCategory(), $_description, 'description') ?>

A: you need to pass the content of the description inside a function before the display. This filterProvider will replace the widget code inside the content of the description.
public function __construct(
    \Magento\Cms\Model\Template\FilterProvider $filterProvider
)
{
    $this->_filterProvider = $filterProvider;
}

public function addWidget($description) {
     $newDescription = $this->_filterProvider->getPageFilter()->filter(
           $description
     );
     return $newDescription;
}

A: I don't know why it doesn't work for you, basically {{widget type="Magento\Cms\Block\Widget\Block" template="widget/static_block/default.phtml" block_id="10"}} should work in cms page, category descriptions etc...
I have some workaround, it is not very best way but try it:

*

*Create phtml in : app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates/html/category-description.phtml
<?php echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId("static-block-indentifier")->toHtml(); ?>

*In your category description area >Wysiwyg editor > show/hide editor > add this:
{{block class="Magento\Framework\View\Element\Template" template="Magento_Theme::html/category-description.phtml"}}

Now you should get your static-block content in your category description.


text:
Q: How to get a specific branch by url? Git In my server, I've written a bash script that gets last changes from my Github repo.
I pull the latest master branch with url as following:
git pull myuser:mypassword@github.com/myrepo.git
Now I want to get a specific branch in this bash script? Not clone, I want to pull a specific branch. Is it possible to do that with URL?

A: The manual page for git pull summarises the command format as:
git pull [<options>] [<repository> [<refspec>…]]

*

*<options> are all the optional arguments beginning with -

*<repository> is specified either as a URL or a pre-configured "remote"

*<refspec> is most commonly the name of a branch

So in your example, you have a repository argument of myuser:mypassword@github.com/myrepo.git, and can add a branch name as the <refspec> to give quite simply:
git pull myuser:mypassword@github.com/myrepo.git some-branch-name

More commonly, you would set up a "remote", which is just an alias for that repository URL:
# set up once
git remote add some-memorable-name myuser:mypassword@github.com/myrepo.git
# use from then on
git pull some-memorable-name some-branch-name

That's why you'll see plenty of examples online of commands like git pull upstream master - upstream refers to some particular remote repository, and master is the branch to fetch and merge.


text:
Q: How to evaluate $x^2+iy^2$ on the line from 1 to i? I want to evaluate $$\int_\gamma f$$, where $f(x+yi) = x^2 + iy^2$, and $\gamma$ is the line joining $1$ to $i$.
I want to know the hint. How to calculate $f(z)$?
(The answer is $-\frac{2}{3}$).

A: Hint:
Substitute $y=1-x$ and calculate $$\int_{x=1}^{x=0}f(x,y)dz$$where $$dz=dx+idy=(1-i)dx\\f(x,y)=x^2+i(1-x)^2$$


text:
Q: Refresh the page from the Lightning component I am having the Lightning component that uses the Lightning Data Services to update the fields on the Case record, it works fine if the component is updating fields like status or origin like that. But when I try to update the record type/owner the page is  not refreshed after the update happens.
Below is the component where I am updating the record type and Owner basically it is like transfering the case from one Dept to another
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global"  >
<aura:attribute name="loaded" type="Boolean" default="false" />
<lightning:spinner variant="brand" alternativeText="Loading..." class="{!(v.loaded? 'slds-show': 'slds-hide')}" />
 <lightning:recordEditForm aura:id="form"
        objectApiName="Case"
        recordId="{!v.recordId}"
        onsubmit="{!c.handleSubmit}"
        onerror="{!c.handleError}"
        onsuccess="{!c.handleSuccess}">
        <lightning:inputField aura:id="statusInput" fieldName="Status" class="slds-hide" />
        <lightning:button variant="brand" type="submit" label="SF Support" />
 </lightning:recordEditForm>
</aura:component>

Controller
({
    handleSubmit: function(component, event, helper) {
        component.set('v.loaded',true);
        event.preventDefault();
        var fields = event.getParam('fields');

        fields.OwnerId = 'xxxxxxxxxx'; // Owner is SF Support
        fields.RecordTypeId = 'YYYYYYYYYYYYY';
        fields.Status = 'New';
        console.log(JSON.stringify(fields));
        component.find('form').submit(fields);

    },

    handleError: function(component, event, helper) {
        component.set('v.loaded',false);
        const fieldErrors = event.getParam('output').fieldErrors;
        const separator = ' ';

        let errMessage = Object.values(fieldErrors).map(field => {
            return field.map(error => error.message).join(separator);
        }).join(separator);

        $A.get("e.force:showToast")
        .setParams({
            type: 'error',
            mode: 'pester',
            message: errMessage  }).fire();
    },

    handleSuccess: function(component, event, helper) {
        component.set('v.loaded',false);
        $A.get("e.force:showToast")
        .setParams({
            type: 'success',
            message: 'Case passed to Salesforce Support!',
            mode: 'pester'
        })
        .fire();
    }
})

Though the Owner/RecordType is updated the page is not refreshed. Below screesnshot shows the page is not refreshed , I should be seeing the Owner as SF Support but it still shows the old owner Services  but Toast is fired saying the case is passed.

But when do the full page refresh it shows up SF Support. Can anyone please help me what I am missing here


text:
Q: Tabularx ignores initial skip in \rowcolors{Skip}{Color1}{Color2} Here is a MWE with initial skip 3:
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{tabularx}
\begin{document}
\begin{table}
  \rowcolors3{blue!20}{green!20}
  \caption{With tabular}
  \begin{tabular}{*3{p{0.33\columnwidth}}}
    \hline
    Time  & Money   & Length \\
    \hline
    Contemporary \\
    Sec   & \$      & inch   \\
    Hour  & cents   & cm     \\
    \hline
    Ancient \\
    ?     & Dinar   & Yard   \\
    horae & Drachma & Palm   \\
    \hline
  \end{tabular}
\end{table}
\begin{table}
  \caption{With tabularx}
  \rowcolors3{blue!20}{green!20}
  \begin{tabularx}{\columnwidth}{XXX}
    \hline
    Time  & Money   & Length \\
    \hline
    Contemporary \\
    Sec   & \$      & inch   \\
    Hour  & cents   & cm     \\
    \hline
    Ancient \\
    ?     & Dinar   & Yard   \\
    horae & Drachma & Palm   \\
    \hline
  \end{tabularx}
\end{table}
\end{document}

EDIT
Indeed, a duplicate. But, the short answer: tough luck buddy, is not so immediate in the original.


text:
Q: Find the type of the item at the current position in a C# editor window I am writing an extension to Visual Studio intellisense and would like to get the type of the item just before the cursor in a C# editor.
I currently have a ITextBuffer which I can use to get the current source file.
I can also get the current position in the editor as below:
var dte = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE._DTE)) as EnvDTE.DTE;
TextSelection sel = (TextSelection)dte.ActiveDocument.Selection;

However I'm not too sure how to detect the type of the item currently behind the cursor in the editor. I've tried using Roslyn but it seems like this should be a much simpler thing to do than this. Is Roslyn the best tool to do this (via compiling the document and navigating to the correct position in the document) or is there a better way.
Below is my attempt at finding the type of the item using Roslyn:
ITextSnapshot snapshot = m_textBuffer.CurrentSnapshot;
SnapshotPoint? triggerPoint = session.GetTriggerPoint(snapshot);

var tree = SyntaxTree.ParseCompilationUnit(m_textBuffer.CurrentSnapshot.GetText());

var nodes = tree.GetRoot().DescendantNodes();

var element = nodes.Where(n => n.Span.End <= triggerPoint.Value.Position).Last();

var comp = Compilation.Create("test", syntaxTrees: new[] { tree });
var semModel = comp.GetSemanticModel(tree);

//I cant work out what to do here to get the type as the element doesnt seem to be of the required type
var s = semModel.GetTypeInfo((AttributeSyntax)element);

A: The compiler API's are very deliberate and require you to ask the right question (no fuzzy logic.) Simply finding the type of the thing at the cursor position requires some context, and the answer that might seem obvious to you at first may not be the correct answer for other uses.
For general expressions you can do something like this:  (Note it is not very robust)
var root = tree.GetRoot();
var token = root.FindToken(pos);
var nearestExpr = token.Parent.AncestorsAndSelf().OfType<ExpressionSyntax>().First();
var type = semModel.GetTypeInfo(nearestExpr).Type;

A more comprehensive solution would check the parent node of the token and go from there:
var node = token.Parent;
if (node is ExpressionSyntax)
{
    type = semModel.GetTypeInfo((ExpressionSyntax)node).Type;
}
else if (node is VariableDeclaratorSyntax && ((VariableDeclaratorSyntax)node).Identifier == token)
{
    type = (TypeSymbol)semModel.GetDeclaredSymbol((VariableDeclaratorSyntax)node);
}

...
There are a lot of interesting cases, and what you want to show as the type corresponding to any particular identifier or token in the source file could vary depending on what you are trying to accomplish.


text:
Q: Poker table card effect I did one example just to show scenario I'm right now, I want the cards array on stagger to be showed on close on each player and not in middle as it is in example I did right now.  Can anyone give me an idea of how can I achieve this effect?  If you could fork the codepen demo that would be great.

// just for example
var cards = ['Cards', 'Cards', 'Cards', 'Cards'];

cards.map(function(card) {
  var cardTemp = '' + card + '';

  $('.table').append(cardTemp);
});

TweenMax.staggerTo(".player-card", 1, {
  rotation: 360,
  y: 100
}, 0.5);
.table {
  position: relative;
  max-width: 700px;
  height: 300px;
  border: 1px solid black;
  margin: auto;
}
.dealer {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  color: #fff;
  border-radius: 50%;
  background-color: green;
}
.players {
  position: absolute;
  width: 50px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  background-color: orange;
  color: #fff;
}
.players:nth-child(1) {
  top: 0;
  left: 0;
}
.players:nth-child(2) {
  top: 0;
  right: 0;
}
.players:nth-child(3) {
  top: 50%;
  right: 0;
  transform: translateY(-50%);
}
.players:nth-child(4) {
  right: 0;
  bottom: 0;
}
.players:nth-child(5) {
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}
.players:nth-child(6) {
  left: 0;
  bottom: 0;
}
.players:nth-child(7) {
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}
.player-card {
  position: absolute;
  display: block;
  width: 50px;
  height: 30px;
  background-color: red;
  color: #fff;
  text-align: center;
  line-height: 30px;
  top: 30px;
  left: 50%;
  transform: translateX(-50%);
}

Dealer

Player

Player

Player

Player

Player

Player

Player

Player


text:
Q: what does value ?? 0 means in c# code get { return _a.B; }

set
{
   if (( _a.B.Equals(value ?? 0) != true ))
   {
      _a.B= value ?? 0;
   }
}

I have coded the above code in c#. In the above code what does (value ?? 0) != true mean??

A: ?? is the null-coalescing operator.
Expanded, it means:
value == null ? 0 : value;

Here is the verbose version of your set accessor without the operator.
set
{
   // assumes that this is a nullable type (based on usage)
   int? coalescedValue = value;

   if( coalescedValue == null )
   {
       coalescedValue = 0;
   }

   if( ( _a.B.Equals( coalescedValue ) != true ) )
   {
      _a.B = coalescedValue;
   }
}

There are dozens of discussions on SO regarding the usage of this operator.

A: It's the null-coalescing operator.
As other answers have pointed out, it evaluates the first operand. If that isn't null, then that's the overall value. Otherwise, it evaluates the second operand, and that's the overall value. Importantly though, neither operand is evaluated more than once, and the second operand is only evaluated if the first operand is null. Things are slightly more complicated that due to the potential conversions between types, but that's the general principle.
(At least, that's the theory. There's a bug in the current MS implementation which means the first operand may be evaluated more than once - but it shouldn't be.)
One other useful point to note is that the first operand type must be nullable, but the second doesn't have to be - and in the common case where the first operand is of type Nullable<T> and the second operand is type T, the type of the overall expression is T. So for example:
int defaultValue = 10;
int? potentialValue = GetValueFromSomewhere();
int valueOrDefault = potentialValue ?? defaultValue;

A: If value is null it returns what is after the ??, otherwise it returns the value it's self.
http://msdn.microsoft.com/en-us/library/ms173224.aspx

A: _a.B.Equals(value ?? 0)

can be rewritten as
_a.B.Equals(value == null ? 0 : value)

That means if _a.B is equal to value, if value is not null otherwise equal to zero

A: a ?? b is basically shorthand for
(a != null) ? a : b

which means "give me a, but if a is null, give me the default value of b".
Further the ? : expression is shorthand for:
if (a != null)
   a
else
   b

A: It means that if value == null 0 is returned, otherwise value is returned

A: a = b??c could be seen to expand to:
if(b != Null) {
    a = b;
} else {
    a = c;
}

or, in another shorthand notation [using the ternary operator]:
a = (b!=Null)?b:c;

A: The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

A: (value ?? 0) != true does not mean anything, it's _a.B.Equals(value ?? 0) != true that means something.
And that something is !(_a.B == (value ?? 0)), that is the opposite of "is _a.B  equals to value if value is not null or equals to 0 if _a.B is null).
You can rewrite the code snippet this way:
set
{
    if (value == null)
    {
        if (_a.B != 0)
        {
            _a.B = 0;
        }
    }
    else
    {
        if (_a.B != value)
        {
            _a.B = value;
        }
    }
}

This is a lot longer, but far more readable!


text:
Q: Easy way of representing multiple inputs in keras? I am working on a CNN implementation in which there are multiple (72) inputs.
Each input is processed the same way, and then they are concatenated together.
Currently, I've written out each input and the process for the 72 which not only looks ugly, but takes up a lot of space (size vs. function).
Is it possible to define multiple outputs using some for loop structure?
I simple need to do this:
input = Input(shape(1,78,3))
conv_1_0 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input)

for 72 different inputs, but all the inputs have the same shape.
currently, I have
input0 = Input(shape(1,78,3))
input1 = Input(shape(1,78,3))
input2 = Input(shape(1,78,3))

conv_1_0 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input0)
conv_1_1 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_1")(input1)
conv_1_2 = Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_1")(input2)

..
Is it possible to do it in some for loop in keras?

A: inputs_list = [Input(shape=(1,78,3)) for i in range(72)]
conv_1_list = [Conv1D(filters = 32, kernel_size = (1,6) , padding = "same" , activation = "relu" , name = "conv_1d_1_0")(input_tensor) for input_tensor in inputs_list]

Does that work? :-)


text: Q: Is there a way to delete one output port from flow entries? openvswitch, a flow entry can have a list of actions (e.x. multiple ports for output). Is there a way that I can remove one specific output port from the action list?


text:
Q: Carousel items are not rendered correctly after data Loads from angularjs I'm new in angularjs and working on a ajax loading item carousel with angular, when I put items static in carousel it work fine but when I put ng-repeat to render dynamic the rendered items are not right and it looks like that the carousel js is not working on them and put them in order.
I load the js of the carousel with ng-include and it works fine for static items but not for angular rendered items
What should I do? Am I doing a sequence wrong?
My Controller loading varible:
hmc.Sliders.Episodes.push(Movies);

In my home view:

my slider

{{::slider.title}}

{{::slider.duration_mins}}

It put correctly the data and renders items but not showing correctly
But it show items correctly for static ones:

sliders

This is how it's look like:
Click here to see the image

A: I fount the answer myself and the problem was js was loading before angular finish getting data, so I made the carousel a directive and made a setTimeout(function(){},500)  for items to be rendered.
here is where I found the soloution:
Applying angularjs ng-repeat to owl-carousel


text:
Q: Copying a basic list You will have to forgive me for asking this but I can't seem to find the exact answer to my question. I need to know how to copy this list:
List<String> jpmcRouting

into a new List (the name doesn't matter).
I have found answers on copying an ArrayList but not a standard list. I've tried a lot of solutions but nothing seems to work. I would appreciate any help!

A: List<String> myCopy = new ArrayList<String>(jpmcRouting);

does the job.  Collections.copy is not what you want; that only works if the destination list already has the right number of elements.

A: The simplest way for me is:
List<String> copy = jpmcRouting.stream().collect(Collectors.toList());

if your result doesnt depend on order of elements in list, you can use
List<String> copy = jpmcRouting.parallelStream().collect(Collectors.toList());

it will work mutch faster, but it can change order of elements

A: I could be wrong, but I think Collections.copy(b, a); will do the trick.

A: Do this:
List<String> b = new ArrayList<String>(jpmcRouting.size());
Collections.copy(b, jpmcRouting);


text:
Q: Need to get the value which is not available in DOM element website
I want to get the value of highlighted field for the validation purpose. but the problem is it's not available in DOM element. Could anyone please guide me on this.
I am using selenium with C# for this automation

A: The value you want is accessible via JavaScript.
Devtools tells me the element is an input with id=amount:

You can then use the console to iterigate the element:

To run this in selenium you use a javascript executor.
You've not specified which language you're working with... so...
In Java:
JavascriptExecutor js = (JavascriptExecutor)driver;
var myValue = js.executeScript("return document.getElementById('amount').value");

in Python:
myValue = driver.execute_script("return document.getElementById('amount').value")

in c#:
var js = (IJavaScriptExecutor) driver;
var myValue = js.ExecuteScript("return document.getElementById('amount').value");

One last note - that element and slider is located within an iframe. You may need to switch frames in order to access it. Let me know if you need support with this.


text:
Q: Unable to run the Get-Service command in Powershell Ubuntu I installed Powershell in Ubuntu and when I try the
Get-Service

command, it returns an error :
Get-Service: The term 'Get-Service' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

What am I doing wrong here? Is Get-Service a windows only command ?
Powershell version is PowerShell 7.1.0

A: As written in the official MS Docs, this commandlet is only available on windows ... Meaning it's not available for macOS nor ubuntu at the moment.


text:
Q: Javascript/Jquery to run function when browser width change? I'm creating a mobile website, but right now client insist on using an original website which is non responsive. That means I will be having two website under the same domain.
Now what I need to do is compare user screen size when loading the webpage and redirect them to the right website.
I can resolve this using javascript below:
  if($(window).width() <= 760){
    document.location = "https://maps.google.com.my/";
    alert('mobile ver');//goto mobile version
  }

but there is another problem, what if the person is browsing the website using
1.smaller screen(computer screen) at first then later decide to maximize the browser screen?
or

*

*switch from portrait view to landscape view, (which has a longer width...)

Is there a function that could trigger every time the browser width change?

A: you need to call to your function inside resize event
$(window).resize(function() {
 //call to your function and check the window width
 });

A: I think you should consider having a single website that uses media queries -- as mentioned in @mattytommo's comment -- to alter layout based on the screen width. I've developed a few websites now that have just one site for mobile, tablets, and desktops using media queries. It's occasionally awkward, but it saves having to have two different sites and thus double the maintenance burden.


text:
Q: Use of "and" and "or" to refer to values for comparison I've gotten into a disagreement with a colleague.  My original sentence was "Determine the maximum value of Boys and Girls."  My colleague thought that the sentence should read "Determine the maximum value of Boys or Girls."
I can't find any material on this and I gather that it is quite possible that both are correct.
My question is related to the use of "and" or "or" in the sentence, which one is correct?  An additional posting my me has provided additional details.

A: "or" is not the solution. You need to add an "of" before "Girls".


text:
Q: Powers of polylogarithms I would like to take powers of arbitrary order to polylogarithm functions. For instance, given
$$
\text{Li}_\alpha(z) = \sum_{k=1}^\infty \frac{z^k}{k^\alpha}
$$
I am interested in
$$
[\text{Li}_\alpha(z)]^m = \left(\sum_{k=1}^\infty \frac{z^k}{k^\alpha}\right) ^m
$$
Of particular interest is how the integral representation
$$
\text{Li}_\alpha(z) = \frac{z}{\Gamma(\alpha)}\int^\infty_0dt \frac{t^{\alpha-1}}{e^t-z}
$$
would behave in this case. Does anyone know of research in this area ?

A: well:
$$\ln(1+z)=\sum_{k=0}^\infty\frac{(-1)^{k+1}}{k}x^k$$
so:
$$\ln(1-z)=-\sum_{k=0}^\infty\frac{x^k}{k}$$
$$\therefore \operatorname{Li}_1^m(z)=(-1)^m\ln^m(1-z)$$

If we first try and start with a function of the form:
$$\frac{d}{dx}\operatorname{Li}_a(x)=\sum_{k=0}^\infty x^{k^a-1}=\frac1x\sum_{k=0}^\infty x^{k^a}$$
maybe there is a way to find a function that is represent by this? :)


text:
Q: ten out of ten horseshoes -- meaning?
"Mastering Regular Expressions is the definitive guide to the subject, and an outstanding
  resource that belongs on every programmer's bookshelf. Ten out of Ten Horseshoes."—Jason Menard, Java Ranch

What does that mean?

A: It's the web site's rating system.
It's common, in America anyway, to rate the quality of something on a scale, usually from 1 to 10, sometimes from 1 to 5. So if you say, "I give this one a 5 on a scale of 1 to 10", you're saying it's in the middle. Of course you could use any number for the highest rating but it's common to use either 5 or 10.
This is often described as a number of "stars". Like, "I give this movie 4 stars". See Amazon.com, for example, where they routinely rate products with 1 to 5 stars.
Sometimes people use something other than stars to be consistent with the theme of their book or website or wherever they are giving these ratings. In this case, the site is called "Java Ranch", so the writer is apparently trying to have a ranch theme, and so he uses horseshoes instead of stars.


text:
Q: convert InstanceContextMode.Single to InstanceContextMode.PerCall I have a WCF service that takes 5 min to load everything from a database. I want to get the best performance out of WCF and found this article http://theburningmonk.com/2010/05/wcf-improve-performance-with-greater-concurrency/
it states i will get better performance using PerCall. I have anywhere between 2000 and 4000 hits per second.
my problem is it takes a long time to load the data. per the article it's saying create a wrapper to the real service using a static variable.
i am not sure how that looks and i have no idea what _container really is.
Any chance someone can give me a full example of the below?

In cases where the initialization steps are lengthy and unavoidable, or your class require a number of parameters in the constructor (for instance, when you programmatically host a service retrieve from an IoC container) the parameterless constructor can become a problem. To get around this, you could create a wrapper for your class and expose the wrapper as the service instead but hold a static instance of the underlying service which all the requests are passed on to:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyServiceWrapper : IMyServiceWrapper
{
    // get the underlying service from the container
    private static IMyService MyService = _container.Resolve<IMyService>();

public MyServiceWrapper()
{
    // parameterless constructor which does nothing, so easy to constructor
}
public void DoSomething()
{
    MyService.DoSomething();
}

}
// dummy interface to ensure the wrapper has the same methods as the underlying service
// but helps to avoid confusion
public interface IMyServiceWrapper : IMyService
{
}

For a sessionful service, the PerSession instance context mode gives
  you all the benefit of the PerCall instance context mode and at the
  same time reduces the overhead you pay for that extra concurrency
  because new instances of your class are no longer created for each
  request but for each session instead.

A: You can remove the logic of fetching service object from IOC container:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MyServiceWrapper : IMyServiceWrapper
    {
        // get the underlying service from the container
        private static IMyService myService = new MyService();

        public MyServiceWrapper()
        {
            // parameterless constructor which does nothing, so easy to constructor
        }
        public void DoSomething()
        {
            myService.DoSomething();
        }
    }

    // dummy interface to ensure the wrapper has the same methods as the underlying service
    // but helps to avoid confusion
    public interface IMyServiceWrapper : IMyService
    {
    }


text:
Q: PHP POST with header() and Bad header problems I've come across a dumbfounding issue with sending headers in PHP. I've spent about 45 minutes reading on SO and other sites and I can't come up with a legitimate reason for my problem.
I need to send a POST request to another server and I'm using the PHP header() function to set the values.  I have sample code below.
    $server = 'http://fakedomain.com';
    $server_path = '/';
    $request = 'key=value&key2=value2';
    header("POST $server_path HTTP/1.1" );
    header("Host: $server\r\n" );
    header("Content-type: application/x-www-form-urlencoded\r\n" );
    header("Content-length: ".strlen($request)."\r\n" );
    header("Connection: close\r\n\r\n" );
    header($request);

I've tried a variety of options but each of them results in the same error in my log file
malformed header from script. Bad header=POST / HTTP/1.1: php5.cgi

I'm an experience PHP programmer who just hasn't had much need to manually send HTTP post requests.
I want the code to redirect the browser so that's why I decided to use this method.
Am I doing it right?
Is there some other way that is standard and I just don't know about?

A: header() sends a response header.
It sounds like you want to make a request, on the back end.
So you probably want to use curl to make the request.
If when you're done processing the response, you want to send some kind of header to the user agent (browser), then header() would be appropriate.

A: The header functions relate to the headers returned to the client, I suggest you look into using cURL to do your post request: http://www.php.net/cURL

A: If you want to redirect user to another page, you should use
header("Location: http://domain.com/some.other.page?x=y");

If you want the user to send POST variables to the redirect page you will need to use JavaScript.
<html>
<head>
<title>Redirect</title>
</head>
<body onload="document.myform.submit()">
<form name="myform" action="http://domain.com/some.other.page" method="POST">
<input type="hidden" name="x" value="y">
</form>
</body>
</html>

A: Expanding on timdev's answer, here's the cURL you'd use:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.target.com/script.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "postvar1=value1&postvar2=value2&postvar3=value3");
curl_exec ($ch);
curl_close ($ch);
?>

A: I have tried simple html form posting it worked for me
    <?php
    if( $dev === 'sample1' || $dev === 'sample2' )  {

?>
    <form name="frmpostdata" action="mystatement.php" method="post">
        <input type="hidden" name="cmsReq" value="MobApp" />
        <input type="hidden" name="cardno" value="<?php echo $chkTkn['cardno'];?>" />
        <input type="hidden" name="cardPwd" value="<?php echo $chkTkn['pwd'];?>" />
        <input type="submit" style="display:none;" name="Submit" value="" />
    </form>
    <script>
        document.frmpostdata.submit();
    </script>
<?php
        exit;
    }
    ?>


text:
Q: Exporting to PDF: scale changes print area I have read similar questions, but I haven´t been able to do what I want in a quick way.
I want to export the area that I am seeing. For that, for example the scale is 1:8000, but I want the resolution of scale 1:2500.
In both options to export (Export map as PDF or with Composer) when I select the scale of 1:2500, the layout is reduced.
The only solution I have found is this: Export as PDF, copy the four coordinates in a notepad, change scale and, finally, copy the coordinates from notepad to QGIS. But I think there must be a more simple way.


text:
Q: HTTPCookieStorage not persisting a cookie I couldn't find anything in the docs but did read on a forum that HTTPCookieStorage does not persist a cookie whose expirationDate is null. Is this indeed the case? And if so, what's the best way to make it so it does persist it (forever)?

A: Typically, you would set a ridiculously far-future date, e.g. twenty years from the date that you set the cookie.  And, of course, whenever you connect to the server again, you would also typically bump that expiration date to twenty years from that point.
Or if you're doing this in code (rather than on the server), you can probably use [NDSDate distantFuture].


text:
Q: protobuf-net version without system.servicemodel dependency? Just a quick question - is there a protobuf-net distro without the system.servicemodel and WCF tie-ins? Or i would need to fork on github and compile my own?
It's a headache because i'm trying to use protobuf in a SQL CLR environment (don't ask...) and that thing requires the entire reference tree statically registered before it allows any execution - and system.servicemodel fans out to 22 assemblies this way, which understandably does not make DBAs happy, even if none of those 22 actually get loaded.
Oh and it needs to be for .net 3.5 a la SQL Server 2008


text:
Q: Remotely Updating Raspberry Pi Software 'over the air' We use a Raspberry Pi embedded computer to connect IP cameras on a customers network to our cloud based recording service.
We are using Raspbian and about 50% are Wheezy and 50% are Jessie.
The challenge we have is how to remotely update the software running on these IFUs.
Our current method involves using SSH and Ansible. We have a complex Ansible script that makes all the changes to the Raspberry Pi and we have automated this to an extent so we can updates lots of Raspberry Pi's at a time.
However, the problem is is that this is a non-atomic update. The Raspberry Pi's do not necessarily always have exactly the same package versions on them depending on when they were updated. Its also possible for an upgrade to fail half way through etc.
I am aware that there are a couple of ways of doing an atomic upgrade by downloading a new 'software image' and swapping over to using it instead using a bootloader. I think OpenWRT can do this as well as swupdate: https://github.com/sbabic/swupdate
Has anyone ever done something like this on a Raspberry Pi before?
Thanks

A: As a bit of an update to this question, I found a couple of ways of doing this.
The first thing to consider is that you do not have to stick with the RPI's default bootloader as @user3145836 pointed out. Uboot allows you to flip the boot partition.
The best option at the moment appears to be https://mender.io and this is the option that we have gone with.
If you can dockerize your app, https://resin.io/ is a nice hosted way of doing it.


text:
Q: How do i pass arguments while running a bat file in Jenkins I want to run a bat file located in a specific location with some parameters.
If i cd to that location and then run the bat file with arguments, it works in command prompt. But how do i run it with absolute path in Jenkins?
I want to do something like this
call "C:\Program Files (x86)\SmartBear\soapUI-4.5.2\bin\testrunner.bat C:\Dev\COM\B2B\Vishal\SOAPUIGIT\B2bSoapUI.xml -s"Amend Order New Framework" -M"
however this gives an error saying
"The filename, directory name, or volume label syntax is incorrect."

A: Solved it.
The issue was with the double quotes.
Changing it to this worked
call "C:\Program Files (x86)\SmartBear\soapUI-4.5.2\bin\testrunner.bat" C:\Dev\COM\B2B\Vishal\SOAPUIGIT\B2bSoapUI.xml -s"Amend Order New Framework" -M


text:
Q: Invalid json error when trying to post to web server using CN1 javascript port I get an error 400 from parse.com when trying to post data using the javascript CodenameOne port. The same code works fine in the simulator and mobile app versions.
I followed the Chrome debugging steps mentioned here and it's pretty hard to see what's happening. I see though that the parse4cn1 logging is identical to that on the simulator except that the latter succeeds whereas the javascript call fails:
Log from javascript port:
[parse4cn1] Data to be sent: {"data":{"timestamp":1457471857989,"mood":2,"user":"WQpcT5uzxM"}}
[parse4cn1] Request URL: https://api.parse.com/1/classes/Mood
[parse4cn1] Raw response (as string): {"code":107,"error":"invalid JSON"}

Log from simulator:
[invokeAndBlock2] 0:0:18,928 - [parse4cn1] Data to be sent: {"data":{"mood":2,"user":"WQpcT5uzxM","timestamp":1457472171236}}
[invokeAndBlock2] 0:0:18,928 - [parse4cn1] Request URL: https://api.parse.com/1/classes/Mood
[invokeAndBlock2] 0:0:19,348 - [parse4cn1] Raw response (as string): {"createdAt":"2016-03-08T21:22:52.196Z","objectId":"iLrvfxWiYm"}

Any idea what might be going wrong and/or how I can debug this problem in more detail?

A: The above problem disappeared after I hosted the corresponding .war generated by the CN1 build server on open shift (based on this tutorial). So I guess it had to do with the preview html file... strange... but it works now.


text:
Q: ExtJS 4 URL is undefined when I try store.load() I have a Panel with multiple grids. I'm trying to make some kind of global refresh button by which I mean, a button that will refresh all the grids and open tabs, without losing data like when F5 is pressed.
  With two of the grids it was easy just get the store and load it but the third one makes a problem. When I try the same as with the previous two which works OK I get URL is undefined.
  Here is my code:
reloadInstructionsStore: function() {
    var reloadInstructionSt = this.getStore('Instructions');
    var activeCat = this.getActiveCategory();
    reloadInstructionSt.clearFilter(true);
    reloadInstructionSt.filter({
        filterFn: function(item)    {
            return item.get('category_id') == activeCat;
        }
    }),
    reloadInstructionSt.load();
},

The only reason I can think of is that the store that I use here is defined different from the other 2. It's not with PROXY and CRUD, but looks like this:
Ext.define('MY.store.Instructions', {

    extend: 'Ext.data.Store',
    model: 'MY.model.InstructionRecord',

    autoLoad: true,

    data: g_settings.instructionsApi.initialData

});

Is the problem here and is there a way to make things work even like this?
Thanks
Leron

A: You do not need to reload this store, the data is provided on initial page load.  The variable g_settings.instructionsApi.initialData tells me that the data is available as static on the page.  All you need to do in this case is reset the filter, and just remove the reloadInstructionSt.load(); call.
If you actually do want the data to reload from the server, you will need to give your store a url that it can get the data from and the server will have to be able to serve this data up.


text:
Q: Instant image preview not functioning I have an image file input and I am trying to display the image directly after the user uploads the file. I made sure everything else that I am aware of works, however, this piece of code:
<img src={this.state.imgSrc} />

Will only display a tiny image file icon instead of the image itself.
I seriously have no clue what is wrong because I cross-referenced it with multiple different tutorials and those seem to work for some reason. Help much appreciated, Thank you!

A: I'm assuming you're trying to display a preview of the image immediately after the user selects the image and before the user uploads the image.
Here's a Sandbox using an approach that I used with react hooks to show an image preview.
Hope it helps!


text:
Q: Making a beautiful gallery from just thumbnails I am trying to make a gallery that has a fixed html markup that I cannot change. All the modifications I make to this gallery should be with javascript.
My Goal:
To make a gallery from thumbnails that contains the larger version of the image in it's href and show it above the thumbnails on clicking the thumbnail.
In short, I want to turn this: http://i.imgur.com/2EqVjiS.png
into this: http://i.imgur.com/wu000lu.jpg
Limitation:
My jQuery knowledge is very limited.
What I have so far:
You can see what I have developed so far in this live jsbin: http://jsbin.com/eYubAdOy/1
the whole thing is working partially with some bugs. I have added comments for each actions for better understanding.
BUGS:

*

*The second images has a caption; the caption of the second image should be visible only when the second thumbnail is clicked. but, on loading the page, the caption is shown on first image.

*the ajax gif that I added with lazyload doesnt seem to end loading when you load the page.

I would be grateful if someone could help me fix this. and I would also like to know how would you write the whole thing?
Thanks

A: you need to start lazyload after you create the #mainImage like this
//Prepend the big image area. and load the src image of the first thumbnail. The.ast_full is for fancybox integration.
jQuery(".thn_post_wrap .gallery").prepend("

");
//lazyload the big images
jQuery("#mainImage").lazyload();

to fix the caption you need to change this
//if the first thumbail image has caption inside of it, add the caption text to our empty .ast_cap span tag that we appended earlier.
jQuery(".ast_cap").html(jQuery('.has_cap:eq(0) .gallery-caption').html());

for this
if(jQuery('.gallery-item:eq(0) .gallery-caption').length>0){
  jQuery(".ast_cap").html(jQuery('.gallery-item:eq(0) .gallery-caption').html());
}else{
  jQuery(".ast_cap").css("display","none");//hide .ast_cap if it is empty
}

http://jsbin.com/adaQATa/1/edit


text:
Q: Stripping DataFrame column from text to make integer I couldn't find an easy way to do this and none of the complex ways worked. Can you help?
I have a dataframe resulting from a web-scrape. In there I have a data['Milage'] column that has the following result: '80,000 miles'. Obviously that's a string, so I'm looking for a way to erase all content that isnt numeric and convert that string to straigt numbers
'80,000 miles' -> '80000'
I tried the following:
data['Milage'] = data['Milage'].str[1:].astype(int)

No idea what the code above does, I took it from another post from here. But I get the following error message:
  File "autotrader.py", line 73, in <module>
    data['Milage'] = data['Milage'].str[1:].astype(int)
AttributeError: 'str' object has no attribute 'str'

The other solution I tried was this:
data['Milage'] = str(data['Milage']).extract('(\d+)').astype(int)

And the resulting error is as follows:
  File "autotrader.py", line 73, in <module>
    data['Milage'] = str(data['Milage']).extract('(\d+)').astype(int)
AttributeError: 'str' object has no attribute 'extract'

I would appreciate any help! Thank you

A: After some test problem was data is dictionary, you need processing df for DataFrame.
I think you need remove non numeric values and convert to integers:
df['Milage'] = df['Milage'].str.replace('\D','').astype(int)
print(df['Milage'])
0      70000
1      69186
2      46820
3      54000
4      83600
5     139000
6      62000
7      51910
8      86000
9      38000
10     65000
11    119000
12     49500
13     60000
14     35000
15     57187
16     45050
17     80000
18     84330
19     85853
Name: Milage, dtype: int32


text:
Q: How do read-modify-write actions in c++11 achieve mutual visibility when executed by multiple cores? I'm kind of confused about the mechanism behind read-modify-write action, for example, fetch_add. How do they avoid reading the old values and getting the result wrong when using relaxed memory order? here is the demo code:
std::atomic<int> global_counter = 0;

//thread 0
int counter0 = global_counter.fetch_add(1, std::memory_order_relaxed);
assert(counter0 > 0);

//thread 1
int counter1 = global_counter.fetch_add(1, std::memory_order_relaxed);
assert(counter1 > 0);

since both fetch_add actions are tagged with std::memory_order_relaxed, only their atomicity is garanteed. Is it possible that fetch_add actions in both threads read the old values of global_counter(which is 0), and then add on that old values? If it isn't, how do they achieve that?

A: It is not possible. It is achieved by platform specific atomic instruction(s), e.g. using 'lock' prefix in x86 or 'll/sc' on others. The memory ordering controls the observed sequence of the modifications to different memory locations. It's a separate concern from atomicity.


text:
Q: Opportunistic, partially and asyncronously pre-processing of a syncronously processing iterator Let us use Scala.
I'm trying to find the best possible way to do an opportunistic, partial, and asynchronous pre-computation of some of the elements of an iterator that is otherwise processed synchronously.
The below image illustrates the problem.

There is a lead thread (blue) that takes an iterator and a state. The state contains mutable data that must be protected from concurrent access. Moreover, the state must be updated while the iterator is processed from the beginning, sequentially, and in order because the elements of the iterator depend on previous elements. Moreover, the nature of the dependency is not known in advance.
Processing some elements may lead to substantial overhead (2 orders of magnitude) compared to others, meaning that some elements are 1ms to compute and some elements are 300ms to compute. It would lead to significant improvements in terms of running time if I could pre-process the next k elements speculatively. A speculative pre-processing on asynchronous threads is possible (while the blue thread is synchronously processing), but the pre-processed data must be validated by the blue thread, whether the result of pre-computation is valid at that time. Usually (90% of the time), it should be valid. Thus, launching separate asynchronous threads to pre-process the remaining portion of the iterator speculatively would spear many 300s of milliseconds in running time.
I have studied comparisons of asynchronous and functional libraries of Scala to understand better which model of computation, or in other words, which description of computation (which library) could be a better fit to this processing problem. I was thinking about communication patterns and came about with the following ideas:

*

*AKKA

Use an AKKA actor Blue for the blue thread that takes the iterator, and for each step, it sends a Step message to itself. On a Step message, before it starts the processing of the next ith element, it sends a PleasePreprocess(i+k) message with the i+kth element to one of the k pre-processor actors in place. The Blue would Step to i+1 only and only if PreprocessingKindlyDone(i+1) is received.

*AKKA Streams

AFAIK AKKA streams also support the previous two-way backpressure mechanism, therefore, it could be a good candidate to implement what actors do without actually using actors.

*Scala Futures

While the blue thread processes elements ˙processElement(e)˙ in iterator.map(processElement(_)), then it would also spawn Futures for preprocessing. However, maintaining these pre-processing Futures and awaiting their states would require a semi-blocking implementation in pure Scala as I see, so I would not go with this direction to the best of my current knowledge.

*Use Monix

I have some knowledge of Monix but could not wrap my head around how this problem could be elegantly solved with Monix. I'm not seeing how the blue thread could wait for the result of i+1 and then continue. For this, I was thinking of using something like a sliding window with foldLeft(blueThreadAsZero){ (blue, preProc1, preProc2, notYetPreProc) => ... }, but could not find a similar construction.
Possibly, there could be libraries I did not mention that could better express computational patterns for this.
I hope I have described my problem adequately. Thank you for the hints/ideas or code snippets!

A: You need blocking anyhow, if your blue thread happens to go faster than the yellow ones. I don't think you need any fancy libraries for this, "vanilla scala" should do (like it actually does in most cases). Something like this, perhaps ...
def doit[T,R](it: Iterator[T], yellow: T => R, blue: R => R): Future[Seq[R]] = it
    .map { elem => Future(yellow(elem)) }
    .foldLeft(Future.successful(List.empty[R])) { (last, next) =>
       last.flatMap { acc => next.map(blue).map(_ :: acc) }
    }.map(_.reverse)

I didn't test or compile this, so it could need some tweaks, but conceptually, this should work: pass through the iterator and start preprocessing right away, then fold to tuck the "validation" on each completing preprocess sequentially.

A: I would split the processing into two steps, the pre-processing that could be run in parallel and the dependent one which has to be serial.
Then, you can just create a stream of data from the iterator do a parallel map applying the preprocess step and finish with a fold
Personally I would use fs2, but the same approach can be expressed with any streaming solution like AkkaStreams, Monix Observables or ZIO ZStreams
import fs2.Stream
import cats.effect.IO

val finalState =
  Stream
    .fromIterator[IO](iterator = ???, chunkSize = ???)
    .parEvalMap(elem => IO(preProcess(elem))
    .compile
    .fold(initialState) {
      case (acc, elem) =>
        computeNewState(acc, elem)
    }

PS: Remember to benchmark to make sure parallelism is actually speeding things up; it may not be worth the hassle.


text:
Q: Delphi places .exe in unexpected folder ...at least to me it's the wrong folder. Instead of putting the .exe in

d:\projectfolder

it puts it in

d:\projectfolder\Win32\Debug

This is the first time this happens; previously it created the file in the project folder. I've looked in the project options, but I can't seem to find the .exe location there. How can I change this back?
(I'm using XE3)

A: Project -> Options -> Delphi compiler -> Output directory. Thats the place where you change your setting.

A: You can always replace ".\$(Platform)\$(Config)" with ".\" and it will output the exe file to the folder where the source code is located.


text:
Q: Admin restricted pages not redirecting to the admin login page Laravel 7 Recently upgraded from Laravel 6 to Laravel 7, the problem I'm having is when I use the url /admin it should redirect to the admin login page this also applies to admin restricted pages if the user isn't logged in. I'm not sure if I need to change something to the routes in my web.php file or in the login controller.
Route::group(['prefix' => 'admin', 'module' => 'Admin', 'middleware' => ['web'], 'namespace' => 'Admin\Controllers'], function() {

    // Login and Logout Routes
    Route::get('login', ['as' => 'login', 'uses' => 'Auth\LoginController@showLoginForm']);
    Route::post('login', ['as' => 'login', 'uses' => 'Auth\LoginController@login']);
    Route::post('logout', ['as' => 'logout', 'uses' => 'Auth\LoginController@logout']);

    // Password Reset Routes
    Route::post('password/email', ['as' => 'password.email', 'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail']);
    Route::get('password/reset', ['as' => 'password.request', 'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm']);
    Route::post('password/reset', ['as' => '', 'uses' => 'Auth\ResetPasswordController@reset'])->name('password.update');
    Route::get('password/reset/{token}', ['as' => 'password.reset', 'uses' => 'Auth\ResetPasswordController@showResetForm']);
});

Login Controller
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function showLoginForm()
    {
        return view('Admin::auth.login');
    }

A: Fixed this issue has an error in my terminal Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255. Which means I forgot to do the upgrade for this https://laravel.com/docs/7.x/upgrade#symfony-5-related-upgrades.