text:
Q: Action Selenium I have moveToElement in builder action and doesn't work. The error is in the line 19.
   builder.moveToElement(nav.findElement(By.className("dropbtn"))).build().perform();
The error is:

Exception in thread "main"
  org.openqa.selenium.UnsupportedCommandException: POST
  /session/91b7605c-441d-444a-b98c-e8001bb79144/moveto did not match a
  known command (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 3 milliseconds Build info:
  version: 'unknown', revision: 'c7b525d', time: '2016-09-01 14:52:30
  -0700' System info: host: 'Torre-Raul', ip: '192.168.1.10', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version:
  '1.8.0_101' Driver info: org.openqa.selenium.firefox.FirefoxDriver
  Capabilities [{rotatable=false, raisesAccessibilityExceptions=false,
  appBuildId=20160823121617, version=, platform=XP, proxy={},
  command_id=1, specificationLevel=0, acceptSslCerts=false,
  browserVersion=48.0.2, platformVersion=10.0,
  XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=Firefox,
  takesScreenshot=true, takesElementScreenshot=true,
  platformName=Windows_NT, device=desktop}] Session ID:
  91b7605c-441d-444a-b98c-e8001bb79144  at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
  Source)   at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)   at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at
  org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at
  org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at
  org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:631)
    at
  org.openqa.selenium.remote.RemoteExecuteMethod.execute(RemoteExecuteMethod.java:35)
    at
  org.openqa.selenium.remote.RemoteMouse.mouseMove(RemoteMouse.java:89)
    at
  org.openqa.selenium.interactions.MoveMouseAction.perform(MoveMouseAction.java:39)
    at
  org.openqa.selenium.interactions.CompositeAction.perform(CompositeAction.java:50)
    at Main.main(Main.java:19)

public static void main(String[] args){
        FirefoxDriver nav = new FirefoxDriver();
        nav.manage().window().maximize();
        Actions builder = new Actions(nav);
        nav.navigate().to("http://www.w3schools.com/howto/howto_css_dropdown.asp");
        builder.moveToElement(nav.findElement(By.className("dropbtn"))).build().perform();
        nav.findElement(By.linkText("Link 1")).click();
    }


text:
Q: Why do variables in the global scope get assigned to the window object? var foo = 'bar';
console.log(window.foo); // bar

Seems like variables get assigned as properties to this, but inside anonymous functions, this refers to the parent scope, but doesn't assign variables to the parent scope.
function() {
    var foo = 'bar';
}();

window.foo; // undefined

What object do variables get assigned to in non-global scopes?

A: To cite http://perfectionkills.com/understanding-delete/#execution_context:

Every execution context has a so-called Variable Object associated
  with it. Similarly to execution context, Variable object is an
  abstract entity, a mechanism to describe variable instantiation. Now,
  the interesing part is that variables and functions declared in a
  source text are actually added as properties of this Variable object.
When control enters execution context for Global code, a Global object
  is used as a Variable object. This is precisely why variables or
  functions declared globally become properties of a Global object

Yet, these Variable Objects are not accessible. The only non-internal one is the global object, window or this (in global context).
The relevant section in the specification is #10: Executable Code and Execution Contexts.

A: In JavaScript, all variables are assigned to some scope object. However, only the scope object of global variables is accessible in JavaScript in the browser through the window object. Variables in a function scope are assigned to some scope object used internally by the JavaScript runtime, but this cannot be accessed by the user.
In another environment, global variables may be accessible as properties of another object (such as GLOBAL in node.js) or may be inaccessible (such as application scripts running inside the Windows Script Host).

A: They're available only in the function they're declared in.
Function scope is the only other scope in JavaScript, btw, unlike block-scoping in other {} languages.)
Re: your edit Don't be fooled--JS's this semantics are a bit irksome IMO--this may not be what you expect under a variety of circumstances.

A: Inside self-invoking anonymous function eg:
function() {
    ....
}()

All variables remain inside it and do not attach themselves to global object or window. Using that technique, there are patterns created such as module/singleton pattern.
Notice that in JS, variables have function-level scope.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we add custom objects in BG96 LwM2M implementation? We have successfully created a client using the LwM2M implementation on BG96 device.
According to the documentation the following LwM2M objects are implemented:

*

*Security object

*Server object

*Access control object

*Device object

*Connectivity monitoring object

*Location object

*Connectivity statistics object

*Firmware update object

*Software management object

*Device capability management object

These objects send the data to server in their own constraint environment. The AT commands that are given in documentation are used to configure the files that helps us to deploy a client on our device.
Now the problem that we are facing is that we want to send our own custom next to the server e.g. the values of a sensor. There isn't any AT command present which can send our sensor values through LwM2M, nor can we edit or create our own lwM2M object that can fulfill this functionality.
In simpler words the LwM2M objects mentioned above transmit their own specific data but we are unable to find a way to send our own custom text/sensor values to the server using LwM2M protocol.
How can we add new resources in the client for customization?

A: I figured it out. The stock firmware of BG96 does not support lwM2M custom objects. To use custom objects you need to use BG96 QuesOpen solution.


text:
Q: How can I rotate an ImageView? I want to rotate an ImageView programmatically in my Activity. Currently I couldn't find any solutions for Xamarin which works and translated solutions from Android didn't work either. Does anybody know how to rotate an ImageView?
This code for example just gives me a NullPoinerException and I don't know why:
[Trace] error opening trace file: No such file or directory (2)
[Mono] Image addref mscorlib[0xb7c3b4b8] -> mscorlib.dll[0xb7c771b0]: 1
[Mono] AOT module 'mscorlib.dll.so' not found: Cannot load library: load_library[1093]: Library '/data/data/ImageViewRotation.ImageViewRotation/lib/mscorlib.dll.so' not found
[Mono] GC_MAJOR: (mature allocation failure) pause 1.41ms, total 1.34ms, bridge 0.02ms major 112K/32K los 0K/0K
[Mono] Assembly mscorlib[0xb7c3b4b8] added to domain RootDomain, ref_count=1
[Mono] Assembly Loader probing location: '/data/data/ImageViewRotation.ImageViewRotation/files/.__override__/ImageViewRotation.dll'.
[Mono] Image addref ImageViewRotation[0xb7c6aac0] -> /data/data/ImageViewRotation.ImageViewRotation/files/.__override__/ImageViewRotation.dll[0xb7c6a4a0]: 2
[Mono] Assembly ImageViewRotation[0xb7c6aac0] added to domain RootDomain, ref_count=1
[Mono] AOT module '/data/data/ImageViewRotation.ImageViewRotation/files/.__override__/ImageViewRotation.dll.so' not found: Cannot load library: load_library[1093]: Library '/data/data/ImageViewRotation.ImageViewRotation/lib//data/data/ImageViewRotation.ImageViewRotation/files/.__override__/ImageViewRotation.dll.so' not found
[Mono] Assembly Loader loaded assembly from location: '/data/data/ImageViewRotation.ImageViewRotation/files/.__override__/ImageViewRotation.dll'.
[Mono] Config attempting to parse: '/data/data/ImageViewRotation.ImageViewRotation/files/.__override__/ImageViewRotation.dll.config'.
[Mono] Config attempting to parse: '/Users/builder/data/lanes/monodroid-mlion-monodroid-4.12-series/a1e3982a/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/ImageViewRotation/ImageViewRotation.config'.
[monodroid-gc] GREF GC Threshold: 46800
[Mono] Image addref Mono.Android[0xb7c506d8] -> Mono.Android.dll[0xb7c6c678]: 1
[Mono] Assembly Mono.Android[0xb7c506d8] added to domain RootDomain, ref_count=1
[Mono] AOT module 'Mono.Android.dll.so' not found: Cannot load library: load_library[1093]: Library '/data/data/ImageViewRotation.ImageViewRotation/lib/Mono.Android.dll.so' not found
[Mono] The request to load the assembly mscorlib v2.0.5.0 was remapped to v2.0.0.0
[Mono] Unloading image mscorlib.dll [0xb7c85a78].
[Mono] Assembly Ref addref Mono.Android[0xb7c506d8] -> mscorlib[0xb7c3b4b8]: 2
[MonoDroid] Xamarin/Android Trial Mode Active
[dalvikvm-heap] Grow heap (frag case) to 10.964MB for 441772-byte allocation
[dalvikvm-heap] Grow heap (frag case) to 12.649MB for 1767052-byte allocation
[] HostConnection::get() New Host Connection established 0xb7c9c840, tid 2126
[Mono] The request to load the assembly System.Core v2.0.5.0 was remapped to v3.5.0.0
[Mono] Image addref System.Core[0xb7cc0320] -> System.Core.dll[0xb7cbf7c8]: 1
[Mono] Assembly System.Core[0xb7cc0320] added to domain RootDomain, ref_count=1
[Mono] AOT module 'System.Core.dll.so' not found: Cannot load library: load_library[1093]: Library '/data/data/ImageViewRotation.ImageViewRotation/lib/System.Core.dll.so' not found
[Mono] Assembly Ref addref Mono.Android[0xb7c506d8] -> System.Core[0xb7cc0320]: 2
[Mono] The request to load the assembly mscorlib v2.0.5.0 was remapped to v2.0.0.0
[Mono] Unloading image mscorlib.dll [0xb7cc2168].
[Mono] Assembly Ref addref System.Core[0xb7cc0320] -> mscorlib[0xb7c3b4b8]: 3
[Mono] Assembly Ref addref ImageViewRotation[0xb7c6aac0] -> Mono.Android[0xb7c506d8]: 2
[Mono] DllImport attempting to load: '__Internal'.
[Mono] DllImport loaded library '(null)'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for '_monodroid_gc_wait_for_bridge_processing'.
[Mono] Probing '_monodroid_gc_wait_for_bridge_processing'.
[Mono] Found as '_monodroid_gc_wait_for_bridge_processing'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for '_monodroid_get_identity_hash_code'.
[Mono] Probing '_monodroid_get_identity_hash_code'.
[Mono] Found as '_monodroid_get_identity_hash_code'.
[Mono] The request to load the assembly mscorlib v2.0.5.0 was remapped to v2.0.0.0
[Mono] Unloading image mscorlib.dll [0xb7d9b5f0].
[Mono] Assembly Ref addref ImageViewRotation[0xb7c6aac0] -> mscorlib[0xb7c3b4b8]: 4
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for '_monodroid_gref_inc'.
[Mono] Probing '_monodroid_gref_inc'.
[Mono] Found as '_monodroid_gref_inc'.
[Mono] DllImport searching in: '__Internal' ('(null)').
[Mono] Searching for '_monodroid_gref_log_new'.
[Mono] Probing '_monodroid_gref_log_new'.
[Mono] Found as '_monodroid_gref_log_new'.
[MonoDroid] UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
[MonoDroid] at ImageViewRotation.MainActivity.OnCreate (Android.OS.Bundle) <0x000c2>
[MonoDroid] at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) <0x00048>
[MonoDroid] at (wrapper dynamic-method) object.f34fad60-56f9-4f99-879a-ff280dbcc703 (intptr,intptr,intptr) <0x0001f>
[mono]
[mono] Unhandled Exception:
[mono] System.NullReferenceException: Object reference not set to an instance of an object
[mono]   at ImageViewRotation.MainActivity.OnCreate (Android.OS.Bundle bundle) [0x00000] in <filename unknown>:0
[mono]   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_savedInstanceState) [0x00000] in <filename unknown>:0
[mono]   at (wrapper dynamic-method) object:f34fad60-56f9-4f99-879a-ff280dbcc703 (intptr,intptr,intptr)
[mono-rt] [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
[mono-rt]   at ImageViewRotation.MainActivity.OnCreate (Android.OS.Bundle bundle) [0x00000] in <filename unknown>:0
[mono-rt]   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_savedInstanceState) [0x00000] in <filename unknown>:0
[mono-rt]   at (wrapper dynamic-method) object:f34fad60-56f9-4f99-879a-ff280dbcc703 (intptr,intptr,intptr)

MainActivity.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Graphics;

namespace ImageViewRotation
{
    [Activity (Label = "ImageViewRotation", MainLauncher = true)]
    public class MainActivity : Activity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            ImageView image = FindViewById<ImageView> (Resource.Id.imageView1);
            Matrix mat = new Matrix();
            Bitmap bMap = BitmapFactory.DecodeResource(Resources, Resource.Id.imageView1);
            mat.PostRotate(45);
            Bitmap bMapRotate = Bitmap.CreateBitmap(bMap, 0, 0, bMap.Width, bMap.Height, mat, true);
            image.SetImageBitmap(bMapRotate);
        }
    }
}

Main.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:src="@drawable/Icon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/imageView1" />
</LinearLayout>

A: The line
Bitmap bMap = BitmapFactory.DecodeResource(Resources, Resource.Id.imageView1);

Is where your app will fail. Why? The Resource Id you are passing in is not for an actual image, but for the ImageView instance. DecodeResource is used for decoding images and not views.
Instead you should do something like:
var drawable = image.Drawable;
using (var bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Config.ARGB_8888))
using(var canvas = new Canvas(bitmap))
{
    drawable.SetBounds(0, 0, canvas.Width, canvas.Height);
    drawable.Draw(canvas);

    var mat = new Matrix();
    mat.PostRotate(45);
    using(var bMapRotate = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, mat, true))
        image.SetImageBitmap(bMapRotate);
}


text:
Q: Touchpad pointing but not clicking in Ubuntu 16.04 LTS I've been facing a problem with my touchpad each time my laptop shuts down because of empty charging. It stops working altogether then it's fixed by itself.
Yesterday it stopped working entirely, so I updated the GRUB config using:
sudo -H gedit /etc/default/grub

I changed the GRUB_CMDLINE_LINUX_DEFAULT from "quiet splash" TO "i8042.reset quiet splash"
NOW the touch-pad is only pointing without the ability to click
I installed Mouse and Touch-pad indicator and seems everything should be working well but it's not working.

My laptop is : Lenovo Thinkpad E460
The OS is : Ubuntu 16.4 - 64 bit


text:
Q: Nodejs - keepAlive indication that same connection is used I've recently implemented a keepAlive in my nodejs application like so:
var keepAliveOptions = {
  keepAlive: true,
  maxSockets: 1,
  keepAliveMsecs: 1000
};

and then passing 'keepAliveOptions' under 'agentOptions' in the request.
In the response I'm able to see 'keepAlive: true'.
But is there a way to check how many times the connection was used? or if it was changed?
In addition, is there a recommended number of sockets to use for keep-alive?
Thanks in advance.

A: The request.connection object, which is a <net.socket>, will be the same for each request which reuses a socket. You could add a listener to the connect event of this socket object to count how many times each socket is used.
Here is a basic example, relevant if you are using the http module in your application:
server.on("connection", function(connection) {
  connection.number_of_times_used = 0;
});

server.on("request", function(request) {
  request.connection.number_of_times_used++;
  console.log("Request used " + request.connection.number_of_times_used + " times")
});

To answer your last question: There is no recommended number of sockets to use for this, as each application will have different requirements and different numbers of users. In your case, I would stick with 1 until you notice any performance issues, and then you can adjust the maxSockets value accordingly.


text:
Q: How do I use constructer for a class with a class as a field in C# Entity Framework Core? I am just getting started with Entity Framework Core within C#, and I'm trying to set up a class structure where one class has a field that is another class. I have found that, when the classes do not have constructors, the code runs fine. However, when I introduce a constructor as follows:
    public class InterestEF
    {
        public InterestEF(string id, int numTimesInterestSelected, AdminEditEF lastEdit, ICollection<AdminEditEF> allEdits)
        {
            this.id = id;
            this.numTimesInterestSelected = numTimesInterestSelected;
            this.lastEdit = lastEdit;
            this.allEdits = allEdits;
        }

        [Key]
        public string id { get; set; }
        public int numTimesInterestSelected { get; set; }
        public AdminEditEF lastEdit { get; set; }
        public virtual ICollection<AdminEditEF> allEdits { get; set; }
    }

    public class AdminEditEF
    {
        public AdminEditEF(string id, string adminIdEditedBy, DateTime dateEdited, string changesMade, string reasonsForChanges, string idOfEditedEntity, EntityTypeEdited entityTypeEdited)
        {
            this.id = id;
            AdminIdEditedBy = adminIdEditedBy;
            this.dateEdited = dateEdited;
            this.changesMade = changesMade;
            this.reasonsForChanges = reasonsForChanges;
            this.idOfEditedEntity = idOfEditedEntity;
            this.entityTypeEdited = entityTypeEdited;
        }

        [Key]
        public string id { get; set; }
        public string AdminIdEditedBy { get; set; }
        public DateTime dateEdited { get; set; }
        public string changesMade { get; set; }
        public string reasonsForChanges { get; set; }
        public string idOfEditedEntity { get; set; }
        public EntityTypeEdited entityTypeEdited { get; set; }
    }

    public class MySQLEFContext : DbContext
    {
        public DbSet<AdminEditEF> AdminEdits { get; set; }

        public DbSet<InterestEF> interests { get; set; }

        public MySQLEFContext(DbContextOptions<MySQLEFContext> options): base(options) { }

    }

I get the following error:
System.InvalidOperationException: 'No suitable constructor found for entity type 'InterestEF'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'lastEdit' in 'InterestEF(string id, int numTimesInterestSelected, AdminEdit lastEdit)'.'

Basically, I'm just wondering if it's possible to have a class that has classes as fields that also has a set of constructors with parameters I can call elsewhere within code?
Any help would be greatly appreciated.
Thank you so much for reading!

A: From the docs:

*

*EF Core cannot set navigation properties (such as Blog or Posts above) using a constructor.

So you would need a constructor that looks like this:
public InterestEF(string id, int numTimesInterestSelected)
{
    this.id = id;
    this.numTimesInterestSelected = numTimesInterestSelected;
}

Or a parameterless one:
public InterestEF()
{
}


text:
Q: Jest without NPM or YARN? Is it possible to install Jest for VS Code without a package manager like NPM or YARN?
I am at a loss for what I should do next, I have tried googling around but all answers seem to point to using NPM or YARN. Unfortunately, I can not use a package manager in my situation. Any help would be greatly appreciated.


text:
Q: How to get second text of p tag of article tag which have same class? I am using beautifulsoup to scrape data from website.
I want to fetch title and abstract from the pages and store it.
I am able to fetch the title however I am facing issue in extracting abstract because the abstract has the same css class as the article tag of title.
Website:http://www.globalbigdataconference.com/santa-clara/global-artificial-intelligence-virtual-conference-125/speaker-details/aaron-burciaga-114059.html
What I have tried so far:
tempURL = 'http://www.globalbigdataconference.com/santa-clara/global-artificial-intelligence-virtual-conference-125/speaker-details/aaron-burciaga-114059.html'

page = requests.get(tempURL)
soup = BeautifulSoup(page.content, 'lxml')
Tag = soup.find_all('h4', class_ = 'clearfix Roboto-Medium font13 sbl-t t-b-m0')
Value = soup.find_all('h4', class_ = 'clearfix Roboto-Medium font15 sbl-t t-b-m0 dks-t l-h20')
topic = soup.find( 'article', class_ = 'clearfix font14 dkg-t Roboto-Regular t-p15 l-h26')
#print('Topic:' + topic.text)
abstract = soup.select('article > p')[2].get_text()
print(abstract)

The issue I am facing here is that ('article > p')[2] goes on to read the complete page I want it to just read the abstract .

A: You can use .contents to get the text you need.

A tag's children are available in a list called .contents - Docs

Here is how to do it.
import requests
from bs4 import BeautifulSoup

url = 'http://www.globalbigdataconference.com/santa-clara/global-artificial-intelligence-virtual-conference-125/speaker-details/aaron-burciaga-114059.html'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
p = soup.find_all('article', class_='clearfix font14 dkg-t Roboto-Regular t-p15 l-h26')[1]
abstract = p.find('p').contents[0]
print(abstract)

During this session, Aaron Burciaga CAP, will review the methods, critical components, emerging technology and innovative methods for designing and building artificial intelligence and maching learning systems that are "made to stick" by driving adoption and adherence principles as much with the users as with the engineers. Having developed Analytics Centers of Excellence for Fortune 100 Companies, growing and leading teams of over 400 data scientists, and being key advisor to government officials on the establishment of AI programs, Aaron will share how to deliver more "Practical AI".


text:
Q: Firing a function after a checkbox is selected in an Angular form I have a dynamic form with checkboxes in my Angular 6 app. The following code retrieves the data for my component and populates a reactive form:
ngOnInit() {
  this.accountsService.getApprovedInvoicesToBeEntered()
    .pipe(first())
    .subscribe(
      result => {
        this.approvedInvoices = result;
        this.controls = this.approvedInvoices.map(c => new FormControl(false));
        this.form = this.formBuilder.group({
          approvedInvoices: new FormArray(this.controls)
        });
      },
      () => { });
}

updateSubtotal() {
  this.selectedTotal  = this.form.value.approvedInvoices
    .map((v, i) => v ? this.approvedInvoices[i] : null)
    .filter(v => v !== null)
    .reduce((a, b) => +a + +b.total, 0);
}

}
This is my html:

         <input type="checkbox" (click)="updateSubtotal()" [formControlName]="i" id="{{i}}">

This works really well, my problem though is that updateSubtotal doesn't take into account the currently clicked item.  If I have a form with invoices and I click the first one then selectedTotal = 0.  When I select a second invoice, the selectedTotal equals the total of the first invoice.
How can I fire the updateSubtotal() function AFTER the checkbox is marked as selected?


text:
Q: The meaning of 'let out a dazed' There is a small part of an story:

'Congratulations, Mark,' Alison said, 'You're the youngest Lottery winner we've ever had. Here's your cheque for $127,000.' I was so shocked, all I could do was let out a dazed, 'Thank you.'

I have looked up the word dazed but it's an adjective and it means confused. Therefore, It is quite unintelligible to me that what a dazed means.

A: Think of "Thank you" (with which the sentence ends) as a single unit that functions as a noun. "Dazed" is an adjective used to describe this "noun".


text:
Q: List of 2d Tensors to one 3d Tensor I have a list of sentences as of word embeddings. So every sentence is a matrix in 16*300, so it is a 2d tensor. I want to connect them to a 3d tensor and use this 3d tensor as input for a CNN model. Unfortunately, I cannot get it into this 3d tensor.
In my opinion, at least connecting two of these 2d tensors to a smaller 3d tensor via tf.concat should work. Unfortunately, I get the following error message
tf.concat(0, [Tweets_final.Text_M[0], Tweets_final.Text_M[1]])

ValueError: Shape (3, 16, 300) must have rank 0

If it works with two 2d tensors I would probably work with one loop
One of these 2d tensors in the list looks like this one:
<tf.Tensor: shape=(16, 300), dtype=float32, numpy= array([[-0.03571776,  0.07699937, -0.02208528, ...,  0.00873246,
    -0.05967658, -0.03735098],
   [-0.03044251,  0.050944  , -0.02236165, ..., -0.01745957,
     0.01311598,  0.01744673],
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ],
   ...,
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ],
   [ 0.        ,  0.        ,  0.        , ...,  0.        ,
     0.        ,  0.        ]], dtype=float32)>

A: You can found the solution in the documentation:
https://www.tensorflow.org/api_docs/python/tf/stack
tf.stack: Stacks a list of rank-R tensors into one rank-(R+1) tensor.
>>> x = tf.constant([1, 4])
>>> y = tf.constant([2, 5])
>>> z = tf.constant([3, 6])
>>> tf.stack([x, y, z])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)>
>>> tf.stack([x, y, z], axis=1)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)>


text:
Q: Covert Time Stamp in HIVE I have a date value (Mon Feb 29 06:01:14 CST 2016) in column. I need to convert this to the format 'YYYY-MM-DD' in hive.
Can any one please help me on this.

A: There is a unix_timestamp function which should help you. to_date(unix_timestamp(your_column, 'EEE MMM dd HH:mm:ss z  yyyy')) This should return a string representing your date.


text:
Q: Image Localisation using images in Assets I found the following issue exists for a long time, And I also find there are many solutions available, But this thread is to get recommended way to do it.
Issue:
We cannot able to localise the images directly from assets folder but we can able to localise the images which we place it in File inspector as shown in the image.

I need to know the answers for the following questions:
- Why we don't have localisation for images in Assets folder ?
- What is the Apple recommended way to localise images ?
Please answer the questions. And if you have any link recommended by Apple please add that with your answers.
Note:
- Its not a duplicate question, am asking this since we know we cannot able to extract / reverse engineer to get the images used in the iOS application assets. But thats not the case with the images placed in the file inspector which can be extracted. So this question is all about Apple's recommended way to approach image localisation and not possible solution.

A: There is not any correct way to localise the xcassets file directly,
but still you can localize the name of the asset to get using your localizable.strings file.
For example:- you want to put any main image at home screen for different different region so you can save that image to xcassets to using their localise name and you can fetch that image like this.
UIImage *img = [UIImage imageNamed:NSLocalizedString(@"Main_image", nil)];

and here is the link from apple that spacify how you can localize the image. LINK


text:
Q: How do I copy the URL contained in the internet shortcut in Windows 7? Sometimes my Internet shortcut doesn't work properly when I double-click on it.
Is there a way to easily copy the URL contained in the shortcut for Windows 7.

A: If you mean a desktop or folder-stored link to a URL, right-click and choose Properties. The URL will already be highlighted for you, so all you have to do is copy it (ctrl+C) and then paste in the address bar of your favorite browser.

A: Right click the link and select 'copy Link Address'; then paste it in the address bar.


text:
Q: Whether Logfile Shrinking is good or bad one for Performance in SQL? I am using SQL Server 2008 R2 database and on our SQL Server instance we have more than 70 databases. In a few databases I can see that the transaction log file size is more than 10 GB. I am shrinking the Tlog file size on a daily basis using the following script:
USE ABC;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE ABC
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (ABC_log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE ABC
SET RECOVERY FULL;
GO

Is there any recommended way to shrink the transaction log file size?

A: Shrinking of log file ON DAILY BASIS like one you do with query you posted is seriously bad and you should NOT do that. The main reason is that after you have shrinked the file it will grow again when new transaction comes and since INSTANT FILE INITIALIZATION is not there for Log files, its only for data files, when log file will grow DB engine will actually have to zero out space to write information so instead of overwriting free space it has to be overwritten with zero values (0×0) and then information can be written. This process takes time and thus delays processing of query
Nice explanation has been done in This link
Please note that instant file initialization is applied to some extent for Tempdb log files even though this is correct you should not shrink tempdb log files on daly basis.
A more simple thought, why to shrink if space has to eventually grow when log informations will be written and log will grow. Its a bad practice, internet is filled with advise not to shrink data files but shrinking log file is equally bad
EDIT: Needless to say( as already pointed out) you are breaking chain of logs by changing recovery model to simple. You loos epoint in time recovery. If point in time recovery is not required kep recovery model of database as simple and log truncations would be handled by DB engine if something is not holding logs and need it in transaction.

A:
... on a daily basis ...
ALTER DATABASE ABC SET RECOVERY SIMPLE;

Yes, this is as bad practice as it gets. Whats the point of having a backup chain if you break it daily?
Now to your question: Does shrinking the log affect performance?
Yes. Indirectly, because you shrink to a way too small file, you are dramatically affecting performance as log needs to grow back to its operational size. Your customers experience painful random delays after your 'maintenance' runs as the database gets frozen to grow and zero-initialize the log file (no instant file growth for log!).
Stop it. Leave the backup chain intact. Determine the operational size of each log file, for each database, grow the log to that size in one operation, leave it so. Monitor log growth events, determine the cause and take appropriate action.

A: Any shrinking of files (data or log) should be done in coordination with your backup strategy - and as others have pointed out it can be a pretty bad idea in many cases (certainly if done regularly).
Side-stepping the exact question slightly: if your log files grow back to the same sort of size in a day or there-abouts then there is obviously something in your workload that requires them to be that size often. By shrinking them you are making what-ever those processes are do more work when they happen as they have to allocate new log space when they need it instead of it being sat pre-allocated and ready for immediate use.
Furthermore I might suggest (if those processes using lots of log space can not somehow be optimised out) setting those sizes as the minimum for the log files and allocating it all at once. This way there is less external (file-system level) fragmentation then there would be if the files each grow in bits over time. This reduction in fragmentation could give a small performance boost to any of the activities that cause a lot of log file use.


text:
Q: Link enumerate item to subsection I have an enumerate like this
\begin{enumerate}
\item this is item 1 in \ref{SectionName1}
\item this is item 2 in \ref{SectionName2}
\end{enumerate}

\section{AAA}
\label{SectionName1}
text
\section{BBB}
\label{SectionName2}
text

This generates something like this:

1 this is item 1 in 1.2
     2 this is item 2 in 1.3
AAA
     text
     BBB
     text

The links in the enumerate are 1.2 and 1.3.
But what I want to do is something different. I want to make the entire item into a link to a section instead of just the section's number. For example:

1 this is item 1
  2 this is item 2
AAA
  text
  BBB
  text

I want that whenever I click on the item's text ("this is item 1" and "this is item 2") to redirect me to the section.
Does anyone know how to do that?

A: I assume you have loaded hyperref. Then \hyperref helps. It supports an optional argument with a label name:
\begin{enumerate}
\item \hyperref[SectionName1]{this is item 1}
\item \hyperref[SectionName2]{this is item 2}
\end{enumerate}

\section{AAA}
\label{SectionName1}
text
\section{BBB}
\label{SectionName2}
text


text:
Q: Speech to Text using Python How can I do a very accurate speech to text conversion using python ? Is it possible to do this with the use of some Python modules ? I have tried speech recognition module but failed to achieve the task. can you guys help ?

A: "very accurate" is depends on your accent. i suggest you:
Google Speech Recognition
English is not the best choice for accuracy, you main language is. (accent)
first, you have to install python 2.x/3.x and pyaudio. then there is an example named "Recognize speech input from the microphone" on that website, you can use it for simple translation.


text:
Q: Java : Map UrlEncoded String to Java Object In a service call I'm am getting UrlEncoded String in response like :
first_name=ABC&last_name=XYZ&age=25&mob=999xxxxxxx&email=xxxxx@gmail.com&city=ABC&state=DEF&country=India

Now, I want the above string to be mapped to a Java Object having the variables name matching the keys from above UrlEncoded string.
It can be done by using delimiter "&" and parsing it to java variables one by one but I'm in search of any direct method or library available to do so because the string I'm recieving in response is large so, logically its not good to parse it one by one. Any help will be appreciated

A: List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), StandardCharsets.UTF_8);

then init your object
Map<String, String> map = params.stream().collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));

    YourObject yourObject = new ObjectMapper().convertValue(map, YourObject.class);


text:
Q: How to get only certain letters from the user. Python I am requesting 2 letters from the user. The user has a choice of 3. Let, these are the letters R, G, B. And the user can enter any pair of them. I need to handle an exception if the user enters anything other than these letters. Any character, number, other letter - must be excluded. I don't know what method to do this.
Maybe i need to create some kind of dictionary of these three letters, and then, when receiving input(), compare with the dictionary? If the input is incorrect, it should write "Enter the suggested values, R, G or B." I lack the knowledge to implement this.


text:
Q: Java BlockingQueue I set an initial capacity of the BQ as 3. But some time producer is going beyond the initial capacity. Plz refer output.
Question Update: ArrayBlockingQueue uses explicit lock for thread safety but in the code i acquire the monitor/implicit lock of sharedResource object.
How to make System.out.println("Produce : "+d); as part of the same explicit lock? /How to achieve the desired output of printing what goes inside the BQ with the same BQ lock?
Declaration
BlockingQueue<String> sharedResource = new ArrayBlockingQueue<String>(3);

Producer
Runnable r = new Runnable() {
    public void run() {
        for (int i = 1; i <= 2; i++) {
            try {

                String d = Thread.currentThread().getName() + "->" + i;
                synchronized (sharedResource) {
                    sharedResource.put(d);
                    System.out.println("Produce : " + d);
                }
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

Consumer
Thread consumer = new Thread(new Runnable() {
    public void run() {
        while (true) {

            try {
                System.out.println("C : " + sharedResource.take());
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});

OutPut
***P1->1
P3->1
P5->1
P2->1***
C : P1->1
C : P3->1
P4->1
C : P5->1
P2->2
P5->2
C : P2->1
P3->2
C : P4->1
P1->2
C : P2->2
P4->2
C : P5->2
C : P3->2
C : P1->2
C : P4->2

Update: I call the producer and consumer as below.
Thread producer1 = new Thread(r);
Thread producer2 = new Thread(r);
Thread producer3 = new Thread(r);
Thread producer4 = new Thread(r);
Thread producer5 = new Thread(r);

producer1.setName("P1");
producer2.setName("P2");
producer3.setName("P3");
producer4.setName("P4");
producer5.setName("P5");

producer1.start();
producer2.start();
producer3.start();
producer4.start();
producer5.start();

consumer.start();

A: The answer is pretty simple in ArrayBlockingQueue#take() method
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html#take()
It says when you call take it "Retrieves and removes the head of this queue, waiting if necessary until an element becomes available."
So it reduces the queue size by 1 so
consider
1. you have 4 elements in queue
2. you call take()
3. the queue size will reduce to 3
hence you queue does not exceed the size 3 in your case.
You are putting as well as removing values from the queue at the same time so queue size does not exceed 3
However if you slowdown your consumer by Thread.sleep(500); you will get the desired output.

A: If your question is exactly that "the 4th output P2->1 is strange" as I described in comments.
Here is my answer:
The BQ works well but this is the problem of the synchronization with BQ operation and System.out
If you want your output correct, the following block
sharedResource.put(d);
System.out.println("Produce : " + d);

should be a atomic operation, either to
System.out.println("C : " + sharedResource.take());

But since put and take already block the thread, it is not easy to merge the System.out into the lock of put and take.
I do not know what is your purpose to print the messages. If just for testing whether Java BQ works well, I promise you "yes".
If you really want your correct output, I recommend you to implement your own BQ and make System.out inside the lock.


text:
Q: PM scaffold-dbcontext not creating a primary key I am reverse engineering our db.  I am using scaffold-dbcontext in the package manager console with the -force flag.  I know for sure it is updating the files.
I have added a Primary key in the db though and when that didn't work I even added another Index:

The dbcontext that was created seems to have the code for the Primary Key:
modelBuilder.Entity<DealerDisclaimers>(entity =>
    {
        entity.HasKey(e => e.DealerDisclaimerId)
            .HasName("PK_DealerDisclaimers");

However, when I try to navigate to a page that would load that table it gives the following error:

InvalidOperationException: The entity type 'DealerDisclaimers'
  requires a primary key to be defined.

The DealerDisclaimers class the scaffold-dbcontext builds out looks like this:
public partial class DealerDisclaimers
    {
        public int DealerDisclaimerId { get; set; }
        public int DealerId { get; set; }
        public string GeneralDisclaimer { get; set; }
        public string LeaseDisclaimer { get; set; }

        public virtual Dealer Dealer { get; set; }
    }

Side note: If I add the [Key] attribute then it loads without the error.  But I shouldn't have to manually add it, the scaffold-dbcontext command should prepare everything for me.

A: Simply adding -DataAnnotations to the scaffold code added the key appropriately for me.
So my script looked like this:
Scaffold-DbContext "Server=MyServer;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Force -DataAnnotations


text: Q: How to automatically back up Linux server SD cards with the installation bit for bit? I have a home server running Raspberry Pi OS (Raspberry Pi 4) that has a hard drive attached for backups of my other devices. I want to use that backup server to backup the SD card that has the installation of Linux and everything else (config, files, etc) bit for bit, like cloning the SD card, and do the same for a Ubuntu VM running on DigitalOcean (VPN server), my Raspberry Pi 4 based OpenWRT router, among other devices automatically over the network daily while removing old backups automatically and if it was offline at that time to back up once online. What are some possible methods to implementing this?


text:
Q: Issues using PHP !isset and functions I am trying to use PHP !isset and a function to check if the any fields submitted from a HTML form are empty, and if so kill (exit) the script. Only the code I have currently oddly skips right over my !issets and continues. +'s to anyone who can figure this out. :)
// Get fields from HTML form
$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Subject = $_POST["Subject"];
$Message = $_POST["Message"];

// Check to make sure no fields are empty
// If any fields are empty dumps script to fieldsmissing()
// If all fields are filled, continued to write actual email
if (!isset($Name)) {fieldsmissing(); };
if (!isset($Email)) {fieldsmissing(); };
if (!isset($Subject)) {fieldsmissing(); };
if (!isset($Message)) {fieldsmissing(); };

function fieldsmissing () {
exit;
}

A: isset just checks whether a variable is set and not null, not whether it's blank. Try something like:
if (!$Name) {fieldsmissing(); }
if (!$Email) {fieldsmissing(); }
if (!$Subject) {fieldsmissing(); }
if (!$Message) {fieldsmissing(); }

A: function fieldsmissing () { // to declare before calling it
  exit;
}

// Get fields from HTML form
if (!isset($_POST["Name"])) {fieldsmissing(); };
if (!isset($_POST["Email"])) {fieldsmissing(); };
if (!isset($_POST["Subject"])) {fieldsmissing(); };
if (!isset($_POST["Message"])) {fieldsmissing(); };

$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Subject = $_POST["Subject"];
$Message = $_POST["Message"];

// then use $Name etc...

A: php5 -r '$x="";if(isset($x)){print "isset\n";}'

returns:
isset

isset gives true for empty strings.
empty() can be much more useful. php.net/empty

A: $Name = $_POST["Name"]; will cause a warning if $_POST["Name"] is not available from the form.
You should probably do this instead:

$Name = ( isset( $_POST["Name"] ) ? $_POST["Name"] : '' );
if ( empty( $Name ) )
{
fieldsmissing();
}

HTH

A: Don't use isset to check if filed was filled because it'll return true on empty string!
Instead use empty() function.
if (!isset($_POST['Name']) || empty($_POST['Name'])) {fieldsmissing(); }

Also, you don't have to use ; after }.


text:
Q: Disable kendo dropdown list Keyboard navigation I want to disable kendo drop down list Keyboard navigation which is the default behavior:
DropDownList / Keyboard navigation
In my specific case I have a drop down inside editable grid and I want to disable changing the  highlights next/previous item when pressing the left/right arrows because I am using these to do another behavior (change focus to next column)

A: I got the answer
It seems that the secret is in turning off the keydown event on dropdown first:
.off("keydown")

here is a working code in Code Pen where I disabled right and left arrows and enabled other keys:
http://codepen.io/MohQut/pen/vEKBvz


text:
Q: How to return plain XML from ADO.NET data service I was wondering how to return plain XML from ADO.net data services
I have exposed an ADO.net data service to different departments in our company who are not so technical. The data returned is ATOM FEED which is some-what hard to read / interpret with its format and too much information is returned.
People from various departments would execute different queries ( HTTP Request) and I would like them to display simple XML or at least something more user friendly like HTML
I have tried ACCEPT attribute of the request to be plain XML and it still returns ATOM

A: If I were you I would use Friendly feeds which is a feature of WCF Data Services, which allows you to map properties to feed fields which would show as proper rss feeds on any rss feed reader, even the default feed reader from IE 7 and 8 would display them and sort them for you.
WCF Data Services Feed Customization
hope this helps

A: ADO.NET Data Services - now known as WCF Data Services - will always return an Atom feed - that's the core of their functioning.
You shouldn't have any trouble, however, interpreting and working with that Atom feed. On the client side, you can just do a Add Service Reference to the service URL, and a nice, clean client-side proxy will be generated, complete with .NET object classes which you can use to read and interpret the output from the WCF Data Service. You can even use LINQ against this client classes to do your queries!
I would recommend you get to know and use Atom, instead of trying to fight it.


text:
Q: opencv-python нет подсказок в Pycharm установил opencv-python через терминал, всё встало без ошибок, но вот с подсказками беда. Выглядит это так:
но код отрабатывает, как положено:
а вот если работаешь в консоли, то там все подсказки есть:
Переустановка Pycharm и питона не помогли, при этом удалял хвосты вручную. На первом скрине у меня видно, что подсказки из cv2, а у людей cv2.cv2 Если написать from cv2 import cv2  ругается

A: Проблема решается копированием файла cv2.pyd из Python310\Lib\site-packages\cv2 в папку Python310\Lib\site-packages

Всем добра!


text:
Q: How do I specify a tuple in a Numba Vectorize signature? I'm defining a function and want to use Numba Vectorize to speed it up, with cuda. I'm having trouble with the function signature. The function will return a float64 value. I want to pass two float64 values, which will be vectorized, and in addition a 9-tuple of float64 values, which will be scalars.
Here is my function header:
from numba import vectorize

@vectorize(['float64(float64, float64, UniTuple(float64, 9))'], target='cuda')
def fn_vec(E, L, fparams):
    # calculations...
    return result

but this gives an error:
TypeError: data type "(float64 x 9)" not understood

I've tried many variations, including (float64, ..., float64) in place of the UniTuple(), but can't get anything to work. How do I do this?

A:
How do I specify a tuple in a Numba Vectorize signature?

In a numba.vectorize function you cannot use a tuple. That's because vectorize vectorizes the code for arrays of these types.
So using a float, float, tuple signature creates a function that expects two arrays containing floats and one array containing tuples. The problem is that there is no dtype for an array containing tuples - it could work if you use a structured array instead of an array containing tuples but I haven't tried that.

How do I specify a tuple in a Numba jit signature?

The correct way to specify a UniTuple in a numba signature is with numba.types.containers.UniTuple. In your case:
nb.types.containers.UniTuple(nb.types.float64, 9)

So the correct signature would be somthing like this:
import numba as nb

@nb.njit(
    nb.types.float64(
        nb.types.float64,
        nb.types.float64,
        nb.types.containers.UniTuple(nb.types.float64, 9)))
def func(f1, f2, ftuple):
    # ...
    return f1

I often avoid typing my numba functions explicitly - but when I do I found it very useful to use numba.typeof, for example:
>>> nb.typeof((1.0, ) * 9)
tuple(float64 x 9)

>>> type(nb.typeof((1.0, ) * 9))
numba.types.containers.UniTuple

>>> help(type(nb.typeof((1.0, ) * 9)))  # I shortened the result:
Help on class UniTuple in module numba.types.containers:

class UniTuple(BaseAnonymousTuple, _HomogeneousTuple, numba.types.abstract.Sequence)
 |  UniTuple(*args, **kwargs)
 |
 |  Type class for homogeneous tuples.
 |
 |  Methods defined here:
 |
 |  __init__(self, dtype, count)
 |      Initialize self.  See help(type(self)) for accurate signature.

So the information is all there: It's numba.types.containes.UniTuple and you instantiate it with two arguments, the dtype (here float64) and the number (in this case 9).

In case you wanted to vectorize over the float arrays only

If you did not want to vectorize the function for the tuple argument you could simply create the vectorized function inside another function and call it there:
import numba as nb
import numpy as np

def func(E, L, fparams):
    @nb.vectorize(['float64(float64, float64)'])
    def fn_vec(e, l):
        return e + l + fparams[1]  # just to illustrate that the tuple is available
    return fn_vec(E, L)

This makes the tuple available inside the vectorized function. However it has to create the inner function and compile it everytime you call the outer function, so this may be actually slower. I'm also not sure that this will work with the target="cuda", you may need to test that yourself.


text:
Q: cross-env issue when running "npm run dev" for vue-cli I'm with Centos7, installed on VirtualBox (true OS: Windows 7).

*

*Node version: 6.10.3

*Npm version: 3.10.10

I installed vue-cli, like this:
sudo npm install -g vue-cli

Then I created a new vue project, like this:
sudo vue init webpack-simple mynewproject

But I get an error when running "npm run dev":
> mynewproject@1.0.0 dev /var/www/html/mynewproject
> cross-env NODE_ENV=development webpack-dev-server --open --hot

sh: cross-env : commande introuvable

npm ERR! Linux 3.10.0-514.el7.x86_64
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! vuetest@1.0.0 dev: `cross-env NODE_ENV=development webpack-dev-server --open --hot`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the mynewproject@1.0.0 dev script 'cross-env NODE_ENV=development webpack-dev-server --open --hot'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the vuetest package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development webpack-dev-server --open --hot
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs vuetest
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls vuetest
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/www/html/mynewproject/npm-debug.log

Does anyone know how to fix it?

A: You need to cd to your project directory and run:
npm install
You can find the instructions on the webpack-simple github repo


text:
Q: Using KQL (kusto query language) to explore data from a local file (e.g. Excel, CSV, JSON etc.) Is there any way to use KQL to query a large local file (10k+ rows) such as Excel, CSV etc. alongside data hosted in Kusto (Azure Data Explorer)?
Here is my scenario:
I extensively use KQL to explore data hosted in Kusto (Azure Data Explorer) clusters. Mostly these explorations are very dynamic and in one-off scenarios to investigate situations.
For some data, I just have Excel and CSV files that I want to join with Kusto data. I know I could do this with Pandas, but I'm specifically asking if there's any way to do it with KQL, preferably without setting up a cluster and ingesting the data into a Kusto table.

A: There are a few ways this can be done, but there is one requirement which is that the data needs to be accessible from the Kusto cluster, for your scenario, the files need to be in Azure Storage. The lightest approach is using the externaldata operator, but you can also set up an external table.
Also please note that you can get your own free cluster to do this processing, to create it go to http://aka.ms/kustofree


text:
Q: Can you change one colour to another in an Bitmap image? For Bitmap, there is a MakeTransparent method, is there one similar for changing one color to another?
// This sets Color.White to transparent
Bitmap myBitmap = new Bitmap(sr.Stream);
myBitmap.MakeTransparent(System.Drawing.Color.White);

Is there something that can do something like this?
Bitmap myBitmap = new Bitmap(sr.Stream);
myBitmap.ChangeColor(System.Drawing.Color.Black, System.Drawing.Color.Gray);

A: Lifting the code from this answer:
public static class BitmapExtensions
{
    public static Bitmap ChangeColor(this Bitmap image, Color fromColor, Color toColor)
    {
        ImageAttributes attributes = new ImageAttributes();
        attributes.SetRemapTable(new ColorMap[]
        {
            new ColorMap()
            {
                OldColor = fromColor,
                NewColor = toColor,
            }
        }, ColorAdjustType.Bitmap);

        using (Graphics g = Graphics.FromImage(image))
        {
            g.DrawImage(
                image,
                new Rectangle(Point.Empty, image.Size),
                0, 0, image.Width, image.Height,
                GraphicsUnit.Pixel,
                attributes);
        }

        return image;
    }
}

While I haven't benchmarked it, this should be faster than any solution that's doing GetPixel/SetPixel in a loop.  It's also a bit more straightforward.

A: Through curiosity to Yorye Nathan's comment, This is an extension that I created by modifying http://msdn.microsoft.com/en-GB/library/ms229672(v=vs.90).aspx.
It can turn all pixels in a bitmap from one colour to another.
public static class BitmapExt
{
    public static void ChangeColour(this Bitmap bmp, byte inColourR, byte inColourG, byte inColourB, byte outColourR, byte outColourG, byte outColourB)
    {
        // Specify a pixel format.
        PixelFormat pxf = PixelFormat.Format24bppRgb;

        // Lock the bitmap's bits.
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        BitmapData bmpData =
        bmp.LockBits(rect, ImageLockMode.ReadWrite,
                     pxf);

        // Get the address of the first line.
        IntPtr ptr = bmpData.Scan0;

        // Declare an array to hold the bytes of the bitmap.
        // int numBytes = bmp.Width * bmp.Height * 3;
        int numBytes = bmpData.Stride * bmp.Height;
        byte[] rgbValues = new byte[numBytes];

        // Copy the RGB values into the array.
        Marshal.Copy(ptr, rgbValues, 0, numBytes);

        // Manipulate the bitmap
        for (int counter = 0; counter < rgbValues.Length; counter += 3)
        {
            if (rgbValues[counter] == inColourR &&
                rgbValues[counter + 1] == inColourG &&
                rgbValues[counter + 2] == inColourB)

             {
                rgbValues[counter] = outColourR;
                rgbValues[counter + 1] = outColourG;
                rgbValues[counter + 2] = outColourB;
             }
        }

        // Copy the RGB values back to the bitmap
        Marshal.Copy(rgbValues, 0, ptr, numBytes);

        // Unlock the bits.
        bmp.UnlockBits(bmpData);
    }
}

called by bmp.ChangeColour(0,128,0,0,0,0);

A: You need a library that provides a way to modify the color space of an image without having to work with pixels. LeadTools has a pretty extensive image library that you can use that supports color space modifications, including swapping colors.

A: You can use SetPixel for that:
private void ChangeColor(Bitmap s, System.Drawing.Color source, System.Drawing.Color target)
{
    for (int x = 0; x < s.Width; x++)
    {
        for (int y = 0; y < s.Height; y++)
        {
            if (s.GetPixel(x, y) == source)
                s.SetPixel(x, y, target);
        }
    }
}

GetPixel and SetPixel are wrappers around gdiplus.dll functions GdipBitmapGetPixel and GdipBitmapSetPixel accordingly
Remarks:

Depending on the format of the bitmap, GdipBitmapGetPixel might not
  return the same value as was set by GdipBitmapSetPixel. For example,
  if you call GdipBitmapSetPixel on a Bitmap object whose pixel format
  is 32bppPARGB, the pixel's RGB components are premultiplied. A
  subsequent call to GdipBitmapGetPixel might return a different value
  because of rounding. Also, if you call GdipBitmapSetPixel on a Bitmap
  object whose color depth is 16 bits per pixel, information could be
  lost during the conversion from 32 to 16 bits, and a subsequent call
  to GdipBitmapGetPixel might return a different value.


text: Q: Is every finite dimension topological linear space locally compact? I know that every locally compact topological linear space X has finite dimension. I also know that A Hausdorff topological linear space is locally compact if and only if it is finite dimensional. But is every finite dimension topological linear space locally compact?


text:
Q: Pass facebook access token from mobile client to server and process I am hoping to work on a REST API that would interface with a mobile client. I am think of implementing the following flow and hope you guys can set me off in the right direction:

*

*User accesses the mobile app and then will signup with facebook (app)

*Once the user successfully authenticates himself, the generated token is passed to the server (via an API endpoint)

*The server will accept this token and will attempt to query the facebook server using this token and process the returned information

Is this possible? And am I heading in the right direction ?

A: Not only this is possible, but this is the approach which Facebook recommends. This is called "token debugging" in FB parlance.
The token will need to be checked and validated by your server, by calling the token debug Facebook api.
If you don't validate the token on the server, your app could be subject to various attacks, e.g. another developer could use a token generated on another app to gain entry.
The correct approach is:

*

*testing that the user is the one to whom the token belongs to

*that your app is the same for which the token was generated

*that the token itself is valid.

You can manually inspect a token, in order to test your code with an online tool: https://developers.facebook.com/tools/debug/


text:
Q: Cannot create the new feed on Azure DevOps. Got an error "Cannot read property 'descriptor' of null" I have created a new organization and then trying to create a new feed on the Artifacts tab for packaging solution. But I cannot do it. I have got an error like "Cannot read property 'descriptor' of null" I'm not sure maybe I something missed in the permission or something like that. Could someone help me? Thanks

A: After creating the first pipeline with pack configuration the problem disappear


text:
Q: How to give different input fields different values on link click I use a function to clear the input values of form fields in a container:
function clear_form_elements(ele) {

$(ele).find(':input').each(function() {
    switch(this.type) {
        case 'password':
        case 'select-multiple':
        case 'select-one':
        case 'text':
        case 'textarea':
            $(this).val('');
            break;
        case 'checkbox':
        case 'radio':
            this.checked = false;
    }
});}

this completely clears a set of input fields inside a div, fieldset or similar (defined as ele). Now I tried to replace the
$(this).val('');

with
if(this.id = "town") {this.val('town');}
if(this.id = "country") {this.val('country');}

to replace input elements with different IDs but the value returned for each input field is always "country" even though the ID of the element is different.
What am I doing wrong?

A: Change:
if(this.id = "town") {this.val('town');}
if(this.id = "country") {this.val('country');}

to
if(this.id == "town") {this.val('town');}
if(this.id == "country") {this.val('country');}

(double equals)
Your statement will always return true after setting values. you are trying to compare, not to set a value.


text:
Q: Cannot create new projects in Platform IO VS-Code plugin After a fresh install of VS Code and PlatformIO I get the following error when simply trying to open a new project. (Note: I'm using Windows 10)
Could not initialize project
PIO Core Call Error: "DLL load failed: The specified procedure could not be found."
I'd really love to start using this tool becasue it seems very useful. Any suggestions would be greatly appreciated.

A: Wonderful news, I have found a simple fix! As usual it is due to yet another one of Microsoft's latest Anti-Features. This time it's Cortatna, that POS I never use but has been quietly haunting my file system for the past year.
Note: this was discovered after investigating numerous other issues with my file system, all of which appear to have the same cause
Option 1, Stay in the dream:

*

*Press  Ctrl + Shift + Esc keys together to Open Task manager.

*Now, Locate Cortana and do a Right Click on it and Choose End task.
Doing this will restart the Cortana process and will Fix the issue... (Temporarily??)

Option 2, (I personally did not try this one):
Install KB4532695 update to fix this
Microsoft have released KB4532695 update which seems to fix this issue for the PC affected by this bug. Just download and install KB4532695 from this official Microsoft website.
Reference:
https://thegeekpage.com/how-to-fix-file-explorer-search-not-working-in-windows-10/
Option 3: Shatter the grand illusion and wake up from the nightmare all together.
To remove Cortana from Windows 10, use these steps:

*

*Open Start.

*Search for PowerShell, right-click the top result, and select the Run as administrator option.

*Type the following command to uninstall Cortana from Windows 10 and press Enter:
Get-AppxPackage -allusers Microsoft.549981C3F5F10 | Remove-AppxPackage
Reference: https://www.windowscentral.com/how-uninstall-cortana-windows-10-may-2020-update
Also, I appears as though MS will not let me uninstall their malware so to get rid of Cortana may require even more work.
Not sure, but you may need to run Step one first if you encounter issues.


text:
Q: Создать не стандартное меню для WordPress Имеется такая структура меню:

                        home

                        about

sub1

sub2

sub3

sub4

sub5

Некоторые пункты меню верхнего уровня являются ссылками a, а некоторые являются span, содержащие вложенный список со ссылками.
Меню подключаю так:
              <?php
                   $args = array(
                        'menu' => 'header-menu',
                        'menu_class' => 'nav navbar-nav nav__top-menu',
                        'container' => 'ul',
                    );
                    wp_nav_menu($args);
                ?>

Но по умолчанию все пункты меню выводятся ссылками а.
Как сделать так, чтобы элемент списка li с классом dropdown содержал в себе не ссылку, а такой спан: ....
Необходима именно такая структура html, т.к. от этого зависит работа библиотеки для responsive menu.

A: Нашла решение тут
Немного изменила:
if ( $args->has_children && 0 === $depth ) {
                $item_output .= '';
            } else {
                if (!empty($item->attr_title)) {
                    $pos = strpos(esc_attr($item->attr_title), 'glyphicon');
                    if (false !== $pos) {
                        $item_output .= 'attr_title) . '" aria-hidden="true"> ';
                    } else {
                        $item_output .= 'attr_title) . '" aria-hidden="true"> ';
                    }
                } else {
                    $item_output .= '';
                }
            }


text:
Q: How to set gap when solving with cplex I am writing code in c++ and calling CPLEX to solve it. It finds a very good solution quickly, but takes a very long time trying to improve it. So I want to set the gap to a larger value to terminate the code, and this is what I use:
    cplex_model.setParam(EpGap, 0.01);

But the compiler gives me an error saying EpGap is an undeclared identifier. What is the default name for relative gap?

A: EpGap is a part of an enum within the class IloCplex
cplex_model.setParam(IloCplex::EpGap, 0.01);

A: cplex_model.setParam(IloCplex::EpGap, 0.01); is correct
If the EpGap is 1 (1%) it goes to the next feasible solution found that gives a duality gap of 1% or less, so once it goes under 1% it should stop and give you that solution.  So in your case, it may go from duality gap > 1% to 0.43%!


text:
Q: How to import PostgreSQL into MySQL database? I have dumped a PostgreSQL database and I would need it to a MySQL as we migrate our project from Heroku to Amazon EC2, where is MySQL.
It's quite a long time when I was doing something similar like raw dumps & SQL queries, so I would like to ask you for help how to make this as smoothly as possible.
I dumped a PostgreSQL database. When I open the file, there are some PostgreSQL commands, table structures and data that belongs to those tables. On the other hand, I have on EC2 a MySQL database with created tables (the same tables as are in the PostgreSQL dump - but all MySQL tables are empty). My goal is to populate the MySQL tables with data from PostgreSQL tables.
How to do that?

A: As of 6 days ago Amazon started offering a hosted PostgreSQL service as part of their Relational Database Service. I would seriously considering importing straight back into PostgreSQL and skipping MySQL altogether. Changing to a different DBMS is always more pain than it's worth.
You can import your dump by running it using psql, like this: psql -f <backup_filename> <target_db>. See Amazon's docs for more
If you're really set on migrating to MySQL you can try a simple tool like openDBcopy or something more comprehensive (and complicated) like Talend Studio.

A: If you have text file created by pg_dump then in this file you can see data from source database as COPY command or as series of INSERT commands. Both should be easy to import to any other database. Maybe you will have to change string representation of dates. COPY format is simply CSV and for this you will have to write import program, for example Jython: Python language that can work with JDBC drivers. With Jython you can easily parse CSV data and import it into destination database using JDBC PreparedStatement with proper INSERT.
If you have connection to both databases at once you can "pump" destination database using various tools. As Jython fan I simply use JDBC with code like:
insert_stmt.setObject(i, rs_in.getObject(i))

where insert_stmt isprepareStatement() with INSERT... and rs_in is record set of executeQuery()


text:
Q: Trying to delete files via a scheduled task and VBScript I asked a previous question about downloading file unattended on a server, using VBScript and Windows Task Scheduler. (See
Scripting SFTP unattended download )
That works great but now I also need to delete the files from the server I am calling:
Set sessionses = WScript.CreateObject("WScript.Shell")

    sessionses.Run "C:\TCS\SFTP\delThem.bat", , True

PSFTP calling a batch file that runs this command:
psftp user@host:22 -batch -b script.txt -pw pa$$word

script.txt is as follows:
cd FromCeridian
del *.GEN

If I run this command from the command line, or double click the batch file containing the command, it works "interactively", but when running unattended and scheduled, it doesn't do this part. The server is SFTP, so I can't just use win ftp commands to do it.
Any ideas?

A: Check the security options of your task to verify the user identity has correct access privileges.


text:
Q: Form builder angular Can't bind to 'formGroup' since it isn't a known property of 'form' hi can someone explain me why i get error like my title ,
i use form builder and also i import reactive form module and forms module in my own module and my app module but still get errorl like this Can't bind to 'formGroup' since it isn't a known property of 'form'
my Component
my Template
my own module
app module

A: You forgot to register AddQuotesComponent in Module. Look at the declaration array you will not find the AddQuotesComponent.


text:
Q: Retornar todas as classes CSS com Expressão Regular Eu preciso retornar todas as classes encontradas dentro de uma string CSS, de modo que quando a expressão fosse conflitada com:
div.classe1{/*...*/}
.classe2 div a{/*...*/}
.classe3.classe4{/*...*/}
.classe5{/*...*/}

Retornasse em um array (com ou sem os pontos antes do nome da classe, tanto faz):
["classe1","classe2","classe3","classe4","classe5"]

O que tentei até o momento foi este código:
\.(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)(?![^\{]*\})

Mas aparentemente não funcionou muito bem...
Segue um FIDDLE para melhor entendimento.

A: Minha sugestão é usar um parser de CSS completo, como o JSCSSP, e extrair as classes dos seletores individuais (em vez do texto do CSS inteiro).
function extrairClasses(css) {
    var classes = [];

    var parser = new CSSParser();
    var sheet = parser.parse(css, false, true);
    for ( var i = 0 ; i < sheet.cssRules.length ; i++ ) {
        var seletor = sheet.cssRules[i].mSelectorText;
        if ( seletor )
            classes = classes.concat(seletor.match(/\.\w+/g));
    }

    return classes;
}

Exemplo no jsFiddle. Note que ele funciona mesmo na presença de casos "degenerados", como um comentário contendo " ou uma string contendo /* (e ambos contendo .classe).

A: Segue implementação em JS puro:
var texto = "div.classe1{background:red}.classe2 div a{background:#00f}.classe3.classe4{background:green}.classe5{background:#ff0}";

var retorno = texto.match(/\.(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)(?![^\{]*\})/ig); //[".classe1", ".classe2", ".classe3", ".classe4", ".classe5"]

Note a inclusão de /ig ao final que pesquisa toda a string (não apenas a primeira ocorrência) em case insensitive.

A: Pensando em tratar a questão de comentários e hacks que começam com ponto, pensei na seguinte função:
function parseClasses(cssSource) {

    //remove comentários
    var semComentarios = cssSource.replace(/\/\*([\s\S]*?)\*\//g, '');

    //remove blocos com a formatação
    var semBlocos = semComentarios.replace(/{\s*[^}]*\s*}/g, '');

    //recupera classes no que restou
    return semBlocos.match(/\.-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g)

}

Exemplo de uso:
var classes = parseClasses(str);
for (var i = 0; i < classes.length; i++) {
    console.log(classes[i])
}

Demo no jsfiddle

A: Podemos analisar string caractere por caractere para eliminar classes que fiquem dentro de comentários /* .classe */, é a melhor forma de se extrair todas as classes CSS de uma string.
$string = <<<EOF
div.classe1{/*comentario div.classe1b*/}
div.-classe2{/*div.-classe2b*/}
div._classe3{/*div._classe3b*/}
.classe4 div a{/*.classe4b div a*/}
.classe5.classe6{/*.classe5b.classe6b*/}
.classe7{/*......classe7b......*/}
.classe8{esse aqui nao tem comentarios mas tambem nao pega o .classe8b pois esta dentro das chaves}
.cl{/*.clb 2 caracteres*/}
.c{/*.cb 1 caractere*/}
.d{/*.db 1 caractere*/}
EOF;

$length = strlen( $string );

$brackets = false;
$comment = false;
$dot = false;
$class = '';
$classes = array();

for ( $i = 0, $j = 0; $i < $length; $i++ ) {
  if ( $string[ $i ] === "\x2f" && $string[ $i + 1 ] === "\x2a" ) {
    $comment = true;
    continue;
  } else if ( $string[ $i ] === "\x7b" ) {
    $brackets = true;
    continue;
  } else if ( $brackets === false && $comment === false && $string[ $i ] === "\x2e" ) {
    $dot = true;
    continue;
  } else if ( $string[ $i ] === "\x2a" && $string[ $i + 1 ] === "\x2f" ) {
    $comment = false;
    continue;
  } else if ( $brackets === true && $string[ $i ] === "\x7d" ) {
    $brackets = false;
    continue;
  }
  if ( $dot ) {
    $j = $i + 1;
    $k = $j;
    if ( ( ( $string[ $i ] >= "\x41" && $string[ $i ] <= "\x5a" ) || ( $string[ $i ] >= "\x61" && $string[ $i ] <= "\x7a" ) || ( $string[ $i ] === "\x2d" ) || ( $string[ $i ] === "\x5f" ) ) === false ) {
      $class = '';
      $dot = false;
      continue;
    }
    $class = $string[ $i ];
    while ( ( $string[ $j ] >= "\x30" && $string[ $j ] <= "\x39" ) || ( $string[ $j ] >= "\x41" && $string[ $j ] <= "\x5a" ) || ( $string[ $j ] >= "\x61" && $string[ $j ] <= "\x7a" ) || ( $string[ $j ] === "\x2d" ) || ( $string[ $j ] === "\x5f" ) ) {
      $class .= $string[ $j ];
      $j++;
    }
    array_push( $classes, $class );
    $class = '';
    $dot = false;
    $i = $j - 1;
  }
}

echo '
';
var_export( $classes );
echo '
';
die();

O resultado obtido da função var_export é o array com todas as classes, e como o objetivo é remover classes que venham a estar presente dentro de comentários, então isso é alcançado com sucesso e além disso também são removidas classes que existam por qualquer motivo que seja dentro de chaves (talvez isso não funcione bem com @media css), mas eu adicionei isso por último pois estou presumindo que seu código seja um código "normal" sem @media css, caso haja presença de @media basta remover as partes referentes aos brackets, no código original que elaborei não tinha o brackets, adicionei agora por último.
Elaborei o código agora depois de ler a pergunta, fiz testes rápidos então não asseguro que está funcionando 100%, mas está extraindo classes que começam com - ou _ ou a-z ou A-Z e procedido ou não de de - ou _ ou a-z ou A-Z ou 0-9.
array (
  0 => 'classe1',
  1 => '-classe2',
  2 => '_classe3',
  3 => 'classe4',
  4 => 'classe5',
  5 => 'classe6',
  6 => 'classe7',
  7 => 'classe8',
  8 => 'cl',
  9 => 'c',
  10 => 'd',
)

P.S: Sei que a categoria é Javascript e o código publicado é PHP, mas fiz questão de responder pelo fato de ser a resposta correta para a sua pergunta e a que obtém os melhores resultados, e também pelo fato da semelhança na sintaxe e funções PHP e JS, para "converter" para Javascript, serão necessárias apenas adaptações mínimas. Espero ter ajudado.

A: Usando expressões regulares, /([^{]+)\s*\{[^}]*}/ satisfaz todos os seletores e /\.(-?[a-z_]+[a-z0-9-_]*)/ todas as classes. Exemplo:
var style = ".class1 { text-align: left; font-weight: bold} " +
            "/* -- Comment -- */" +
            ".class2.class3 { border: 1px solid #a1a1a1 } " +
            "textarea.class4 { height: 400px } " +
            ".class5 ~ .class6 { display: none } " +
            ".class7 .class8:first-child { color: #ababab } ";
function parseCss(stylesheet) {
    var stylesheetPattern = /([^{]+)\s*\{[^}]*}/gm,
        selectorPattern = /\.(-?[a-z_]+[a-z0-9-_]*)/ig,
        classes = new Array(),
        selector, match;
    stylesheet = stylesheet.replace(/(\/\*.*(?!=\*\/)\*\/)/gm, "");
    while(match = stylesheetPattern.exec(stylesheet)) {
        while(selector = selectorPattern.exec(match[1])) {
            classes.push(selector[1]);
        }
    }
    return classes;
}
parseCss(style);

Neste caso, parseCss() retorna [ "class1", "class2", "class3", "class4", "class5", "class6", "class7", "class8" ].


text:
Q: How to generate a QR code for end user payment? We have a requirement to provide UPI payments for our users, we tried the google pay APIs, but it shows the pay button, and also it supports only google pay, we need to support other payment apps as well.
I was planning to generate a QR code with the amount pre-filled.
for example: If I buy a sandwich, the bill might be 100 rs, and the QR code must be generated for that only.

A: You can generate QR code by creating the QR for specific intent.
upi://pay?pa=&pn=&am=&cu=&tn=

where:
pa = Payee address or business virtual payment address (VPA).
pn = Payee name or business name.
am = Transaction amount.
cu = Currency Code.
tn = Transaction note.

Converting this to QR will enable to make payments using any UPI App.
Eg:
upi://pay?pa=anything%40payu&pn=Foody&tn=Order&am=100.34&cu=INR

Javascript code to generate links:
let upi = {
    pa: "anything@payu",
    pn: "Foody",
    tn: "Order",
    am: "100.34",
    cu: "INR"
}
let upiLink = new URLSearchParams(upi).toString();


text:
Q: How to make specific instance of Oracle DB case insensitive? I would like to make specific INSTANCE of Oracle Database 11g Enterprise Edition CASE INSENSITIVE. Cany anyone let me know if this is possible. I already read few blogs where whole DB can be made CASE INSENSITIVE but for specific instance didn't get any idea.

A: You need to play around with NLS_SORT, NLS_COMP parameters. But don't directly implement in production, as you might just hit performance issues if you do not do the extra bit of work required.
I am not sure what you mean by "a specific instance". Is it a RAC environment? Do you want one of the nodes to always have case insensitive sessions?
Anyway, you can do it at SESSION level as well as SYSTEM level. But do you really want to implement the HARD way at SYSTEM level?
For example, at session level :
SQL> alter session set nls_comp='LINGUISTIC';
Session altered
SQL> alter session set nls_sort='BINARY_CI';
Session altered
At system level :
You could have a AFTER LOGON TRIGGER and execute the alter session statements. Eek, but that would be killing the performance. You will have to figure out where all you need to create case-insensitive function-based indexes. In my experience, I have always seen case-insensitive search to be slower, no matter you have the required imdex at place.
You can have a look at my article for detailed explanation, http://lalitkumarb.wordpress.com/2014/01/22/oracle-case-insensitive-sorts-compares/


text:
Q: How to add View Product Detail Link Beside "Add To Cart" Button In WooCommerce? I try to adding a function to display view product detail button beside add to cart . but not working please help me !
  add_action('woocommerce_after_shop_loop_item', 'add_a_custom_button', 5 );
function add_a_custom_button() {
    global $product;
    if( $product->is_type('variable') || $product->is_type('grouped') ) return;
    echo '

        get_permalink() ) . '">' . __('VIEW PRODUCT') . '

';
}

HERE IS IMAGE


text:
Q: Explanation of proof of optimal decoding via factor group Consider an additive map $\varphi\colon\mathbb{F}_2^m\to\mathbb{F}_2^n$ and its image $C$. (Interpret $C$ as a code)
Now, optimal decoding maps $x\in\mathbb{F}_2^n$ to the nearest $c\in C$ in terms of the hamming-distance.
Consider the factorgroup $\mathbb{F}_2^n/C$ and use as representatives of the cosets the elements of the coset of minimum hemming-weight:
$$\begin{array}{rclrrcr}
C &= & \{&0,& c_1,&\dots,&c_{2^m-1}\}\\
b_1+C &=& \{&b_1,& b_1+c_1,&\dots,&b_1+c_{2^m-1}\}\\
b_2+C &=& \{&b_2,& b_2+c_1,&\dots,&b_2+c_{2^m-1}\}\\
& \dots&&&&&\\
b_{2^{n-m}-1}+C &=& \{&b_{2^{n-m}-1},& b_{2^{n-m}-1}+c_1,&\dots,&b_{2^{n-m}-1}+c_{2^m-1}\}\end{array}$$
Now, for $x=b_j+c_i\in\mathbb{F}_2^n$ the nearest code-word is $c_j$, the top-element of x's columns.
I have problems understanding the proof for this theorem, that goes as follows:
Suppose $c_{j_0}$ was sent and $x=c_{j_0}+e$ arrived. Consider the coset $e+C$, and represent it as above: $e+C=b_{j_0}+C$ for some $j_0$. Now, as  $x=b_{j_0}+c_{k_0}$ for some $k_0$, $c_{k_0}$ ist the nearest code-word.
Why? The steps are too big for me.
Thanks alot in advance

A: The key is that we have built this standard array using

as representatives of the cosets the elements of the coset of minimum hamming-weight

(which in general is not required, BTW).
That means that we have chosen $b_i$ (coset leader) as the element with minimum weight inside the coset: $w(b_j) \le w(b_j +C_i)$
Now we receive $x  = C + e $ for some unknown $C$ that we will try to guess (lets call this guess $\hat C$). And we find that $x$ is in the position $(i,j)$ in our standard array, so $x = C_i+ b_j$.
To guess that $\hat C =C_t $ for some $t$ implies to guess an error
$$\hat e= x + \hat C=C_i+b_j + C_t$$
If we choose $i=t$, we get $\hat e= b_j$
Elsewhere , because $C_i + C_t = C_s$, for some $s\ne 0$, we get $\hat e = b_j +C_s$. This corresponds to another element of the same coset.
But we have stated above that $w(b_j) \le w(b_j +C_i)$. Hence the first alternative gives us the guessed error with minimum weight.


text:
Q: PlayerPrefs.Save() вызывается при перезагрузке? Знаю что люди делают PlayerPrefs.Save() дабы избежать сбоев, но при перезагрузке телефона вызветься ли оно само? т.к. оно вызываеться при OnApplicationExit(), считаеться ли перезагрузка и выключения? И что если в телефоне сядет баратея, вызветься ли OnApplicationExit()?

A: Для начала, смотрим документацию внимательно:

In cases when the game crashes or otherwise prematuraly exits, you might want to write the PlayerPrefs at sensible 'checkpoints' in your game.

Из чего можно сделать вывод, что как минимум крэш приложения - ситуация, когда сохранение PlayerPrefs не произойдет автоматически. Так же напипасано, про другие "внештаные" ситуации выключения приложения.
Думаю, что в случае с разрядом батареии или перезагрузке телефона нельзя точно сказать или узнать как поведет себя Unity, потому что это зависит от того, вызываются ли те или иные нативные ивенты в операционной системе того или иного смартфона. Unity в свою очередь подвязывается на те ивенты, которые только может, но если система в определенный случай не вызывает никакого события, то Unity с этим сделать уже ничего не может.
И так как подобные случаи предугадать для всех мобильных ОС достаточно сложно, в качестве хорошей практики, Unity предлагает сохранять данные в PlayerPrefs "логическими пачками" и затем принудительно делать Save(). Я бы не стал полагаться на то, что Save() должен вызваться автоматически (а на практике может и не вызваться) и принудительно сохранял данные.

A:
а может ли какой-то метод 100% вызваться при перезагрузке?

Перезагрузка телефона бывает обычной и хард-ресетом. В случае с хард-ресетом ты никак это не отловишь в любом случае. А вот обычная должна послать ивент OnApplicationQuit() в юнити и он сохранит все автоматически. (кстате, вручную сейв вызывать там НЕ нужно)

т.к. оно вызываеться при OnApplicationExit()

А выключать апликуху тоже можно по-разному. Вот если выключать стандартным способом -- OnApplicationQuit() сработает.
Но если через настройки вырубить - совсем не факт. Я не проверял, но вангую что НЕ сработает.

И что если в телефоне сядет баратея, вызветься ли OnApplicationExit()?

А кто тебе гарантирует что у телефона батарея живая? Ну то есть если батарея там изношенная, то телефон без генерации всяких ивентов просто отключится т.к. будет думать что батарея еще есть, а на практике вольтаж упадет ниже нужной отметки.

Лично мое мнение:

*

*Лучше сохранять настройки вручную СРАЗУ после изменения , а не надеятся на то что это за тебя сделает юнити по какому-либо ивенту.

*Или во время LoadingScreen (если это будет занимать много времени, то юзер все равно это не почувствует)

Но, возможно, я просто параноик :)


text:
Q: How to do I expand this conditional, joint probability? Is $\Pr(y \ , \mu |, H_0)$ equal to $\Pr(y \ | \mu)\Pr(\mu | H_0)$ or $\Pr(y \ | \mu , H_0)\Pr(\mu | H_0)$?

A: Definitely the second one. Maybe the first one.
It's definitely the second one because $Pr(y|\mu,H_0) Pr(\mu|H_0) = \frac{Pr(y,\mu,H_0)}{Pr(\mu,H_0)} \frac{Pr(\mu,H_0)}{Pr(H_0)} = Pr(y,\mu|H_0)$.
It's the first one if we assume that $y$ is independent of $H_0$ given $\mu$, which gives us $Pr(y|\mu,H_0) = Pr(y|\mu)$.

A: It is the second expansion that is the correct one because you need to keep the condition on $H_0$ on both probabilities. Once you have done that, you are allowed to treat the conditional probabilities as regular probabilities and all rules you know apply.
Having said that, often a simplifcation of
$$\Pr \left(A, B | C \right) = \Pr \left(A |B, C \right) \Pr \left(B |C \right) $$
is possible. If, say, you know that the events $A$ and $C$ are conditionally indendent (given $B$), then the first term on the RHS becomes simply $\Pr \left(A |B \right)$.
You will find these rules particularly useful in Bayesian statistics.


text:
Q: C Binary File not updating/reading Below I have provided my code. I am to "deposit" money based on a provided account number. The name and account number and balance are all in the following 'accounts.dat' file.
Herman T Travis 3 $500
Sam L Travis 1 $40
Henry O Billiam 2 $6000

I am unsure if its the way I created my file (with a simple vi editor) or if it is a problem within my code, but when I run it and give the account number and balance to the program does not report the new balance in the file. Any suggestions?
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char first[15];
    char middle[2];
    char last[15];
    float balance;
    long int acct;
} data;

int main() {
    int choice = -1, i = 0, n = 0;
    long int number;
    double amount;
    FILE *aPtr;
    data accounts[50];

    aPtr = fopen("accounts.dat", "ab+");/* Opens file for read/write; appends to file if exist */

    if (aPtr == NULL) {
        printf("File could not be opened");
        exit(1);
    }

    fseek(aPtr, 0, SEEK_SET); /* Moving pointer to start of file*/

    while (fread(accounts + 1, sizeof(data), 1, aPtr) == 1) /* Read and store info in file, into accounts array */

        i++;
        n = i; /* Num. of records in file */

        do {
            printf("Select Option\n" );
            printf("0: Exit\n1: Deposit\n2: Withdrawl\n3: Add Account\n4: Remove Account\n5: Balance Inquiry\n6: View Accounts\n: ");
            scanf("%d", &choice);

            switch (choice) {
              case 0: /* Exit */
                fclose(aPtr);
                break;

              case 1: /* Deposit*/
                fseek(aPtr, 0, SEEK_SET);
                printf("Enter account number:\n");
                scanf("%ld", &number);
                printf("Enter amount to be deposited:\n");
                scanf("%lf", &amount);
                for (i = 0; i < n; i++) {
                    if (accounts[i].acct == number) {
                        accounts[i].balance = accounts[i].balance + amount;
                        fseek(aPtr, i * sizeof(data), SEEK_SET); /* Pointer goes to accountlocation in file*/
                        fwrite(accounts + i, sizeof(data), 1, aPtr); /* Write modified account into file */
                        break;
                    }
                }
                if (i == n) {
                    printf ( "Account does not exist\n" );
                }
                break;
            }
        } while (choice != 0);

    return 0;
}

A: This while loop to read in the data isn't right
while( fread(accounts+1, sizeof(data), 1, aPtr) == 1 ) /* Read and store info in file, into accounts array */
    i++;

It's only reading into accounts[1], so no matter how many accounts are in the file, you'll only have one in the array.
What you want is to do is read each record into accounts[i] which is what the following code does.
while( fread(&accounts[i], sizeof(data), 1, aPtr) == 1 ) /* Read and store info in file, into accounts array */
    i++;

Or better yet, if you work out the size of the file
fseek(aPtr, 0, SEEK_END);
unsigned long len = (unsigned long)ftell(aPtr);

then you know that len divided by sizeof(data) is how many records there are
n = len/sizeof(data);

and you can read all the records in one go.
if(fread(accounts, sizeof(data), n, aPtr) != n)
  {
  /* Oops! Did not read everything in */
  }

This has the added benefit that you could use malloc so that you're not setting a hard limit of 50 accounts.
Also the way you've opened the file isn't quite right as it will append anything you write to the end of the file regardless of what you do with fseek. You need to use "rb+" instead, but if the file doesn't exist, you'll need to create it first with "wb+".

A: Getting the struct populated correctly is is the focus of this answer.
Naming convention for your file indicates it should be a binary file (i.e. .dat is commonly used in the industry for binary files).  But the contents you show clearly indicate it is a text file, so in the following example, I use data.txt as the file name. And as it is a text file, and includes well defined line fields, parsing the contents into a struct will be fairly straight forward
The format of your file is strictly defined, and uses spaces as delimiters.  This is all okay, but choosing a visible delimiter, not normally used in the field content, such as a comma: , would make things easier when a field is not used, such as when no middle name.  But this is not a requirement, and the following example will use space delimiters.
If you will forgive the use of fgets() and strtok() in this implementation  (with little to no error checking/handling), it provides an example of populating the struct with the contents of the data file:
typedef struct
{
    char first[15];
    char middle[2];
    char last[15];
    float balance;
    long int acct;
}DATA;
const char filename[] = {".\\data.txt"};

int lineCount(const char *fname);
DATA * populateData(int lines, const char *fname);

int main(void)
{
    int lines = lineCount(filename);//count number of accounts in file (lines in file)
    DATA *data = populateData(lines, filename);//Create and populate data structure
    if(data)
    {
        ;   //use data here
        free(data); //free data memory when finished using it.
    }

    return 0;
}

int lineCount(const char *fname)
{
    int count=0;
    char line[260];
    FILE *fp = fopen(fname, "r");
    if(fp)
    {
        while(fgets(line, 260, fp)) count++;
        fclose(fp);
    }
    return count;
}

DATA * populateData(int lines, const char *fname)
{
    int i;
    char *tok;
    char *endPtr;
    char line[260];
    DATA *data = calloc(lines, sizeof(*data ));
    if(data)
    {
        FILE *fp = fopen(fname, "r");
        if(fp)
        {
            for(i=0;i<lines;i++)
            {
                if(fgets(line, 260, fp))
                {
                    //get first name
                    tok = strtok(line, " ");
                    if(tok)
                    {
                        strcpy(data[i].first, tok);
                        //get Middle name
                        tok = strtok(NULL, " ");
                        if(tok)
                        {
                            strcpy(data[i].middle, tok);
                            //get last name
                            tok = strtok(NULL, " ");
                            if(tok)
                            {
                                strcpy(data[i].last, tok);
                                //get balance
                                tok = strtok(NULL, " ");
                                if(tok)
                                {
                                    data[i].acct = atoi(tok);
                                    //get acct
                                    tok = strtok(NULL, "$");
                                    if(tok)
                                    {
                                        data[i].balance = strtod(tok, &endPtr);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            fclose(fp);
        }
    }

    return data;
}

A: There is a major bug in your program:
while (fread(accounts + 1, sizeof(data), 1, aPtr) == 1) /* Read and store info in file, into accounts array */

Does not have a { to enclose all the statements in a block. Hence only the first one (i++;) is repeated in the while statement and the rest executes just once.
My suggestions are:

*

*do not write comments at the end of a lines, they tend to make the program less readable.

*use { and } to enclose all commanded statements in blocks.

*put the { on the same line as the if, while, forandswitch` statements (this style is known as Kernighan and Ritchie).

*do not pack statements on one line as if (i == n) { printf("Account does not exist\n"); }
Regarding your program's objective, you cannot easily update a text file as you attempt to. Either read the entire file into memory structures and write the updated contents from the memory or use a binary format with fixed width fields.
The Unix philosophy is to favor the former approach and reserve the latter for larger databases with high level APIs to address concurrent access issues properly.

A: Also add fflush on writing to a file. See your doc on fflush().


text:
Q: Python Keras:input size: train neural network for regression task where each sample observation is array itself My data matrix looks as follows. [dataframe][1]
https://i.stack.imgur.com/BjpHX.png
The observations for each variable itself are an array and I was wondering how I could change the inpu tsize of keras to accept my arrays:
Here is what I have tried but I don't seem to be able to get the input size correct for my data.
Or is there another package thats more suitalbe
Y = dataset[:,13]
def baseline_model():
    model = Sequential()
    model.add(Dense(13, **input_dim=13**, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal'))
    model.compile(los='mean_squared_error', optimizer='adam')
    return model
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasRegressor(build_fn=baseline_model, epochs=50, batch_size=5, verbose=0)))
pipeline = Pipeline(estimators)
kfold = KFold(n_splits=10)
results = cross_val_score(pipeline, X, Y, cv=kfold)


text:
Q: Azure Devops -----Verify a team exists or not by querying the team name--Return true for existing, Return false for not existing (Bash, or AzureCLI) Azure Devops -----Can someone write a function that can Verify a team in the organization exists or not by querying the team name--Return true for existing, Return false for not existing (Bash, or AzureCLI)
AzureOrganization="https://dev.azure.com/ExampleOrganization"
AzureProject="ExampleProject"
az devops configure -d organization= $AzureOrganization project=$AzureProject

Azure Devops -----Can someone also write a function that can Verify an iteration in the organization exists or not by querying the iteration name or iteration path--Return true for existing, Return false for not existing (Bash, or AzureCLI)

A: Edit I now see this question is a duplicate by the same user. Original question: Azure Devops-How to verify whether team has exists in an organization (Azure CLI or Azure Bash)
Verify if a team exists
(az devops team list --project "ExampleProject" --query "[?name=='ExampleTeamName']").Count -gt 0

Verify if an iteration exists
I'm not sure if you want to check the entire Azure DevOps Organization for an Iteration or just a Team Project, but here is a script you can use for a Team Project. I set the depth of the search to 10, but it's up to you to alter the value according to your needs (it's the depth in the Iteration tree structure). You'll have to replace ExampleProject, IterationName and IterationPath by your own.
Search by name:
(az boards iteration project list --depth 10 --project "ExampleProject" --query "children[?name=='IterationName']").Count -gt 0

Search by path:
(az boards iteration project list --depth 10 --project "ExampleProject" --query "children[?path=='IterationPath']").Count -gt 0


text:
Q: Looking for an alternate word for 'Acquisition' I am trying to find an alternative word for acquisition in the context of acquiring a license to a piece of software. I would prefer a word that's shorter to put on a report than the "Number of License Acquisitions."

A: It sounds as though you're trying to come up with a brief wording for an entry in a report that identifies the number of licenses that consumers have acquired from a software company.
If so—and if the primary audience for the report is the software company—it makes sense to frame the wording not as "Number of License Acquisitions" (which looks at the number from the point of view of the licensees), but "Number of Licenses Issued" (which looks at the same number from the point of view of the company). And if you're trying to be concise, there's no need to say "Number of Licenses Issued," because "Licenses Issued" says the same thing.

A: As oldcat says, just say, "Number of Licenses" and that will be understood.  It is certainly shorter.

A: If you're looking for a word with the same meaning as well as a similar "style," procurement seems, in my opinion, to be the most eloquent solution. For a shorter synonym, using gain or gains, in the noun form could also be a succinct substitute.