text:
Q: How to make App Shortcuts for Android app I have read developer guide of android developer official page and I have manage to create shortcut too. but I want to call my own activity (Explicit), instead of (Implicit) which is given in Android guide as an example. here is the URL for that https://developer.android.com/preview/shortcuts.html
I have made my code like this
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
    ShortcutInfo shortcut = new ShortcutInfo.Builder(this,"id1")

            .setShortLabel("Web site")
            .setLongLabel("Open the web site")

            .setIntent(new Intent(this,Shortcut.class))

    .build();

when I run the app I get this error message
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.murtaza.style2, PID: 4187
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.murtaza.style2/com.murtaza.style2.MainActivity}: java.lang.NullPointerException: intent's action must be set
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.NullPointerException: intent's action must be set
                      at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:111)
                      at android.content.pm.ShortcutInfo$Builder.setIntents(ShortcutInfo.java:987)
                      at android.content.pm.ShortcutInfo$Builder.setIntent(ShortcutInfo.java:968)
                      at com.murtaza.style2.MainActivity.onCreate(MainActivity.java:74)
                      at android.app.Activity.performCreate(Activity.java:6679)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.

How can I call an other activity by pressing that shortcut instead of calling any other app?
It's not 3 year old concept of putting shortcuts on home-screen its just announced with android 7.1. I want to know how to call activity by pressing that shortcut.


text:
Q: How to determine the probability for acceptance sampling I have a probability practice problem and the answer but I don't know how they arrived at the solution. Can someone help me with how to approach this? The answer is $0.225$.
"The manager of a small hardware store buys electric clocks in cartons of $12$ clocks each. To see whether each carton is acceptable, $3$ clocks are randomly selected and thoroughly tested. If all $3$ are of acceptable quality, then the carton of $12$ is accepted. Suppose in a certain carton, unknown to the hardware manager, only $8$ of the $12$ are of acceptable quality. What is the chance that the sampling scheme will inadvertently accept the carton?"
I believe that each clock selection is equally likely so each would have a probability of $\frac{1}{12}$. And each combination of selecting $3$ clocks would be $\frac{1}{12} \cdot \frac{1}{12} \cdot \frac{1}{12}$. I have tried building a Venn diagram but it seems there are so many combinations that it is confusing me. I don't know where to go from there.

A: You just have to select 3 clocks of 12 clocks with acceptable quality. In each carton there are 8 acceptable clocks. The manager select the first acceptable clock with probability $\frac{8}{12}$. This is the fraction of number of acceptable clocks and  number of all clocks in the carton. After the first selection $7$ acceptable clocks and $11$ clocks in total remain in the carton. Thus the probability to select the second acceptable clock is  $\frac{8-1}{12-1}=\frac{7}{11}$.  Similar for selecting the third acceptable clock: $\frac{7-1}{11-1}=\frac{6}{10}$.
Let $C_i$ be the event that the manager select the i-th acceptable clock. Then it is asked for
$$P(C_1\cap C_2\cap C_2)=P(C_1)\cdot P(C_2|C_1)\cdot P(C_3|C_1\cap C_2)= \frac{8}{12}\cdot \frac{7}{11}\cdot \frac{6}{10}=\frac{14}{55}\approx 0.255$$
The notation with the events is not so important for calculating the result. I just post it for completeness. It seems that there is a small typo in your solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to build Tesseract 4.0.0 version for iOS? After installing Tesseract through CocoaPods:
pod 'TesseractOCRiOS', '4.0.0'

The function [G8Tesseract version] returns version number 3.03, but I expected to get version 4.0.
I assume the latest version 4.0 with LSTM can be built using cmake, but I do not know how to do it.
I ask those who know to help me build Tesseract 4.0 for iOS from the source code from an open repository: https://github.com/tesseract-ocr/tesseract

A: https://github.com/chaoskyme/Tesseract-OCR-iOS
Tesseract OCR iOS is a Framework for iOS7+, compiled also for armv7s and arm64. Update tesseract version to 4.00.00alpha.
^_^


text:
Q: Partial derivative of such complicated expression? I have the following complicated expression:
$g(\mu,\nu) = \sum_{j\in \mathcal{U}} \underset{i}{\rm max}(\text{log}(\epsilon_{ij})-\mu_i) + \sum_{i \in \mathcal{B}}e^{\mu_i-\nu_iP_i^s-1}+\sum_{i \in \mathcal{B}}\nu_iP_i^G$ ---(1)
I have to take partial derivative of (1) w.r.to $\nu_i$ and equate it to zero i.e., $\frac{\partial g}{\partial \nu_i} = 0$.
My query is that how to take partial derivative of such complicated expression (1).
Any help in this regard will be highly appreciated.


text:
Q: Query Jenkins for last few builds How can query Jenkins using API to know the last few builds that it executed. I don't know the name of build jobs. I just want Jenkins to return the last n builds it executed or the builds executed between 2 timestamps

A: In order to query build results via API , you have to know the job name in Jenkins. You have to append your jenkins job URL with the this suffix /api/json to get the JSON data String.
For ex: If your Jenkins server has a job named A_SLAVE_JOB , then you have to do a  HTTP GET in your java rest client at this end point : http://<YourJenkinsURL>:<PortNumber>/job/A_SLAVE_JOB/api/json
This shall return a String with all the build history URL (with numbers), Last successful build and last failed build status.
You can traverse the subsequent build of a given job using a for loop. All you need is a JSON parser for extracting values from keys in JSON string. You can use org.json library in java to do the parsing.  A pseudocode sample goes like this :
   import org.json.*;
    class myJenkinsJobParser {
    public static void main(String... args){
    JSONObject obj = new JSONObject("YOUR_API_RESPONSE_STRING");
    String pageName = obj.getJSONObject("build").getString("status");

    JSONArray arr = obj.getJSONArray("builds");
    for (int i = 0; i < arr.length(); i++)
    {
        String url = arr.getJSONObject(i).getString("url");
        // just a psuedoCode......
    }

  }
}

A: Just to summarize. The way you have to request info. Below number 0, 5 it's range of latest 5 builds.
curl -g "${SERVER}/job/${JOB}/api/json?pretty=true&tree=builds[number,url,result]{0,5}" \
  --user $USER:$TOKEN


text:
Q: What is the path for the NT AUTHORITY\SYSTEM registry hive? If I open the registry with the SYSTEM account in Windows by using the PSExec tool from SysInternals:
psexec -i -s regedit

and I change an entry, for example, here:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

... I presume that a corresponding NTUSER.DAT file will be modified.
What is the path to this NTUSER.DAT file?

A: Contrary to common intuition, the ntuser.dat file in LocalSystem's user profile folder (\Windows\System32\config\systemprofile) is not the source of HKEY_CURRENT_USER for applications running as SYSTEM. As far as I can tell, it's not actually used for anything, and it contains very little information.
In reality, the HKCU for applications running as SYSTEM is .DEFAULT under HKEY_USERS. (I'll address another common misconception: .DEFAULT isn't the template for new user profiles, ntuser.dat in \Users\Default is.) .DEFAULT is stored on disk in a file called \Windows\System32\config\DEFAULT. See the MSDN article on Registry-backing files.
Also interesting: the list of the backing files for the various Registry hierarchies, including .DEFAULT, can be found in HKLM\SYSTEM\CurrentControlSet\Control\hivelist.


text:
Q: Number of Automorphism (based on Isomorphism) $X, X'$  be two connected graphs  and let $Z$ be there  $Disjoint$  union.  $D=Aut(X) \times Aut(X')$ . How  does $|D|< |Aut(Z)|$ if and only if $X \simeq X'$ ? An example would be helpful.
In Non-Isomorphic case, should  $D$  be lesser  ?
Context:-
See the red-boxed line.

--From "Lecture Notes in Computer Science" by Christoph M. Hoffmann.
It is easy  to see that $D \leq Aut(Z)$. But, I could not comprehend the statement, " $D$ is a proper subgroup iff $X$ and $X'$ are isomorphic." Why $D$ is a proper subgroup ?
Thanks.

A: The real key is that, since $X$ and $X^{\prime}$ are disjoint connected components of $Z$, any automorphism of $Z$ either stabilizes both $X$ and $X^{\prime}$ (in which case it is in $\mathrm{Aut}(X)\times \mathrm{Aut}(X^{\prime})$), or else it switches them (which can only happen when $X\simeq X^{\prime}$).
If $X\simeq X^{\prime}$ then there is some $\tau \in \mathrm{Aut}(Z)$ sending the vertices of $X$ to the vertices of $X^{\prime}$, that means $\tau \not\in D$ and so $D$ is a proper subgroup of $\mathrm{Aut}(Z)$. If $X\not\simeq X^{\prime}$ then there is no such $\tau$ and so $D=\mathrm{Aut}(Z)$ (i.e. $D$ is not a proper subgroup).


text:
Q: wxPython: How to speed up adding large amount of widgets to a grid EDIT: I debugged a little more to realize, that most of the time consumed by action is actually spent creating the widgets, not placing them into sizer. So the question is how to create them faster?
I need to dynamically change the contents of a dialog by adding circa 300 checkboxes.
I use a wx.GridSizer and a loop that adds them, but it is really slow. Is there a way to do it faster? Some method that waits for all widgets to be added and then calculate the positions and sizes manually since I believe that by calling Add method of a Sizer calculates the sizes immediately.
This is a shortcut of what I do:
... #Destroy all widgets we used to have

for el in self.elements:
    _chk = wx.CheckBox(self,-1,el["name"])
    _t1 = wx.StaticText(self,-1,el["age"])
    _t2 = wx.StaticText(self,-1,el["city"])
    self.checkboxes.append(_chk)
    self.gridSizer.Add(_chk)
    self.gridSizer.Add(_t1)
    self.gridSizer.Add(_t2)
self.SetSizer(self.gridSizer)
self.Layout()
self.Refresh()
self.Update()

It takes about a minute to add some 300 elements, I believe there must be a faster way
since e.g. apps like QIP or ICQ displayed lots of contacts in a second :)
Thanks for any clue!
Additionally excuse my english.
Ray

A: I cannot think of any interface that has 300 widgets on it all at once. I don't believe there is a good way to accomplish this. Instead, you should think about redesigning the interface so the user doesn't have to deal with checking 300 checkboxes (or deal with hundreds of any widget). The only widget that might be able to handle that many checkboxes at once would probably be the ListCtrl with the checkbox mixin. See the demo for an example.


text: Q: Bootstrap carousel without active class I really need help. Can i use boostrap carousel without use active. I want to use only .item. Because I'm using wordpress query to generate post. Carousel is not working well with many generate .active. Help me thank.


text:
Q: can i traverse the items in a KTable from an external method i have a kafka topic and a KTable that listens to it.
i want to write a http POST request that will traverse the current items in the ktable, perform some action on them and write back to the topic
so basically i have:
private val accessTokenTable: KTable[String, String] = builder.table(token_topic_name, tokenStoreString)
    val stream: KafkaStreams = new KafkaStreams(builder, streamingConfig)
    stream.cleanUp()
    stream.start()

....
override def refreshTokens = {

    accessTokenTable.mapValues {
        new ValueMapper[String, String] {
            override def apply(value: String) = {
                value
            }
        }
    }.print(token_topic_name)
}

and when i try to call this method nothing is printed/written to the topic
what am i missing? is my only choice is to write the messages from the ktable to hashmap and read it from there? it misses the whole point of ktables?

A:
the correct solution is to use GlobalKTable to avoid "the state store may have migrated to another instance" errors as discussed here.

Since you answered your own question and apparently run into another issue in your follow-up, let me expand on what you said in your answer to help other readers of this question thread.

*

*If you are using a KTable (which is partitioned = each "instance" of a KTable sees only a part of the total table data) Typically, what you need to do is guard against this exception and retry.  Think: try-catch-retry.

*If you are using a GlobalKTable, then you are side-stepping this problem because each instance of a GlobalKTable has a full copy of the entire table data.

Note: Normally, you don't make a decision between KTable vs. GlobalKTable because you want to prevent "state store may have migrated" situations, but because the two abstractions provide different semantics to your application.  For example, there are many good reasons to use a KTable rather than a GlobalKTable -- and if you do, you simply need to be aware of what we just discussed here (which is covered in the docs, too, but apparently not obvious/clear enough considering that you did run into this question).
Hope this helps!

A: after long investigation, the solution is to query the store behind it (rocksDB) and not the table.
as documented here: confluent
the correct solution is to use GlobalKTable to avoid "the state store may have migrated to another instance" errors as discussed here.
this code worked for me in kafka 0.10.2.1:
    private val accessTokenTable: GlobalKTable[String, String] = builder.globalTable(token_topic_name, token_store_string)

    private val stream: KafkaStreams = new KafkaStreams(builder, streamingConfig)
    stream.cleanUp()
    stream.start()
    val store: ReadOnlyKeyValueStore[String,String] = stream.store(token_store_string,QueryableStoreTypes.keyValueStore[String,String]())

....
    override def refreshTokensFlow = {

       store.all.asScala.map( tuple => {
       // logic goes here
           System.out.println(tuple.key + ": " + tuple.value)
       }
    }


text:
Q: Chrome WebRTC Screen Sharing: On stopping screen share, browser window doesn't become active/focused automatically This is regarding Screen Share on Chrome browser using WebRTC.
An example implementaion of Screen Share on Chrome using WebRTC is: https://talky.io
When the user choses to share a different application(say a text editor), that app's window becomes active(focused) and comes on top of browser, and this is as expected...
The Problem
But after sharing this application, when user clicks on the "Stop sharing" button(present on the floating widget provided by Chrome), the previously shared application window remains on top(focussed). Ideally on stopping screen share, the browser window should be brought back on top, as in focussed.
Is there a way to achieve this using Javascript focus method? Or is this something that Chrome should take care of.


text:
Q: Changing quantity label in woocommerce cart page How can i change the quantity label appear in table header in woocommerce cart page ? I need to change the header label of quantity to something else.

A: You need to edit the template file for the cart page.
Does your theme already have a /woocommerce/ folder with each template? If not you should copy the /cart/ folder from /wp-content/plugins/woocommerce/templates/ to /your-theme/woocommerce/ then edit /cart/cart.php and search for "Quantity".
You could also use this trick in your functions.php file to replace everything that says "Quantity" on your site:
add_filter('gettext', 'translate_reply');
add_filter('ngettext', 'translate_reply');

function translate_reply($translated) {
$translated = str_ireplace('Quantity', 'New Label', $translated);
return $translated;
}

Just change "New Label" to whatever you want to call it.


text:
Q: Loopback + Cannot initialize connector "loopback-component-storage" I'm using loopback storage component "loopback-component-storage" to upload files. But problem is after adding this storage component and a Model for it named as Container, I'm not able to migrate models in my application to database.
Following is error what i get
Error: Cannot create data source "storage": Cannot initialize connector "loopback-component-storage": FileSystemProvider: Path does not exist: ./server/files
    at new FileSystemProvider

But I've /server/files directory as well in project described through this
snapshot
Following is datasources.json file
{
  "school": {
    "host": "127.0.0.1",
    "port": 3306,
    "url": "",
    "database": "school_db",
    "password": "root",
    "name": "school",
    "user": "root",
    "connector": "mysql"
  },
  "storage": {
    "name": "storage",
    "connector": "loopback-component-storage",
    "provider": "filesystem",
    "root": "./server/files"
  }
}

Following is model-config.json (partially, not full)
{
  "_meta": {
    "sources": [
      "loopback/common/models",
      "loopback/server/models",
      "../common/models",
      "./models"
    ],
    "mixins": [
      "loopback/common/mixins",
      "loopback/server/mixins",
      "../common/mixins",
      "./mixins"
    ]
  },
  "Container": {
    "dataSource": "storage",
    "public": true
  }
}

Following is Container (to upload/download files)
{
  "name": "Container",
  "plural": "containers",
  "base": "Model",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

And following is my script to update model, say Address
var server = require('./../../server');
var ds = server.dataSources.school;
var tables = ['Address'];
ds.autoupdate(tables, function(er,result) {
  if (er) throw er;

  ds.discoverModelProperties('Address', function (err, props) {
    console.log(props);
  });

  ds.disconnect();
});

Can someone please help me in figuring out the problem, why storage component is throwing exception of that files directory doesn't exist

A: Try adding this in server.js
var ds = loopback.createDataSource({
    connector: require('loopback-component-storage'),
    provider: 'filesystem',
    root: 'server/files'
});

var storage = ds.createModel('storage');
app.model(storage);

check the documentation here too

A: I think issue in root parameter,
"storage": {
      "name": "storage",
      "connector": "loopback-component-storage",
      "provider": "filesystem",
      "root": "./files"
    }

Please refer : Link
https://strongloop.com/strongblog/working-with-file-storage-and-loopback/

A: Do you have a files folder created inside the server folder?
If no? you have to create a folder named "files"
If yes? then your path declaration might be wrong. Try using full path like this
"root": "/home/ubuntu/Documents/project/server/files"

A: Just add another dot in front of your root directory.
"root": "../server/files"

The problem is your updation or migration script cannot find the directory.
For me the migration script was in a bin directory and this directory structure was one level above.
Once the migration is done revert back.


text:
Q: HQL - Delete with JOIN error Im trying to execute an HQL delete with join.. After soon searching I found that I need to create a query just like suggested HERE:
http://dasunhegoda.com/1093-you-cant-specify-target-table-table_name-for-update-in-from-clause/104/
This is my query:
    dao.executeByHql(
        "DELETE FROM FinalGradeResult e WHERE e.id IN "
        + "( SELECT id FROM "
            + "( SELECT x FROM FinalGradeResult x "
            + "where x.student.id = :studentId "
            + " AND x.classDiscipline IN " +
                + "(SELECT cd from ClassDiscipline cd "
                + " where cd.clazz.id = :clazzId ) ) as X )",
    new HqlParameter("studentId", student.getId()),
    new HqlParameter("clazzId", from.getId()));

But I keep getting this error:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:( near line 1, column 94 [DELETE FROM xxxxxxxxxxxx.entity.FinalGradeResult e WHERE e.id IN ( SELECT id FROM ( SELECT x FROM xxxxxxxxxxxxxxx.entity.FinalGradeResult x where x.student.id = :studentId AND x.classDiscipline IN (SELECT cd from xxxxxxxxxxxxxxxx.entity.ClassDiscipline cd where cd.clazz.id = :clazzId ) ) as X )]

The error points out that the second ( is wrong, the one right after "SELECT id FROM"
EDIT I ve tried like this and same error occours:
    dao.executeByHql(
        "DELETE FROM FinalGradeResult e WHERE e.id IN "
        + "( SELECT id FROM "
        + "( SELECT x FROM FinalGradeResult x "
            + " where x.student.id = :studentId "
            + " AND x.classDiscipline.clazz.id = :clazzId )"
        + " as X )",

EDIT 2 : The query like this doesnt work because of the problem described on the link I've posted in this question:
dao.executeByHql(
        "DELETE FROM FinalGradeResult  e WHERE e.id IN " + "( SELECT x.id FROM FinalGradeResult as x "
                + " where x.student.id = :studentId " + " AND x.classDiscipline.clazz.id = :clazzId )",
        new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));

The error is:
Caused by: java.sql.SQLException: You can't specify target table 'tb_final_grade_result' for update in FROM clause

SOLUTION
After trying everything out here's our conclusion:

*

*We cant have only one query directly because we cant have joins on DELETE.

*We cant have only 2 queries (one subquery) because we have a MYSQL BUG (described on the link provided)

*We cant have 3 queries (2 subqueries) because we cant have a subquery in the FROM clause. That's why our second query doesn´t work (select * from (select ...)) is invalid.

So I decided to use NativeSQL to solve the problem:
dao.executeBySQL(
        "   delete from tb_final_grade_result where id in "
                + " (select * from ( select finalgrade1_.id from tb_final_grade_result finalgrade1_ cross join tb_class_discipline classdisci2_ "
                + " where finalgrade1_.id_class_discipline=classdisci2_.id and finalgrade1_.id_student= :studentId and classdisci2_.id_class= :clazzId ) as tmp )",
        new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));

Special thanks to @scaisEdge

A: Why do you need to use in (select on the same table that you are deleting from? Can't you just put the condition in the where clause?
DELETE FROM FinalGradeResult  e WHERE e.student.id = :studentId " + " AND e.classDiscipline.clazz.id = :clazzId )",
    new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));

Also, I'm not sure what you are referring to with the parameter classDiscipline.clazz.id? Is classDiscipline some other entity with a field named clazz that is yet another entity? That's what the query seems to be saying.

A: The problem with your original query is that you are not allowed you have inner selects anywhere but in select and where clauses. Because HQL operates in terms of entities and not tables or columns, selecting from subsets of tables doesn't make sense. See here:

Note that HQL subqueries can occur only in the select or where clauses.

We had a similar issue in our project and I struggled for awhile to find a single query solution, but I'm afraid with MySQL it isn't possible due to HQL's language design.
The best I came up with was to first fetch the ids as a list, and then pass that list as a list parameter to your update. For you it might be something like:
Query idQuery = createQuery("select id from FinalGradeResult gr where gr.student.id = :studentId AND gr.classDiscipline IN (SELECT cd from ClassDiscipline cd where cd.clazz.id = :clazzId"));
//add parameters
List<Number> ids = query.list();
Query entityQuery = createQuery("delete from FinalGradeResult where id in (:ids)");
entityQuery.setParameterList("ids", ids);

query.executeUpdate()

A: could be the position of as X is wrong
and you are repeting x instead of column name ( set ***column_name*** with the proper column name)
"DELETE FROM FinalGradeResult e WHERE e.id IN "
 + "( SELECT id  FROM
    ( SELECT ***column_name ***  FROM FinalGradeResult x where x.student.id = :studentId AND x.classDiscipline IN
    (SELECT cd from ClassDiscipline cd where cd.clazz.id = :clazzId ) as X)  )",

If the sibquery don't work in hibernate then try with a simple query with join
  DELETE FROM FinalGradeResult e
  WHERE e.id in (
     SELECT  id FROM FinalGradeResult x
     JOIN ClassDiscipline cd ON ( cd.cd.clazz.id = :clazzId
                  and  x.classDiscipline = cd.ClassDiscipline )
     WHERE  x.student.id = :studentId);

A: SOLUTION
After trying everything out here's our conclusion:

*

*We cant have only one query directly because we cant have joins on DELETE.

*We cant have only 2 queries (one subquery) because we have a MYSQL BUG (described on the link provided)

*We cant have 3 queries (2 subqueries) because we cant have a subquery in the FROM clause. That's why our second query doesn´t work (select * from (select ...)) is invalid.
So I decided to use NativeSQL to solve the problem:
dao.executeBySQL(
        "   delete from tb_final_grade_result where id in "
                + " (select * from ( select finalgrade1_.id from tb_final_grade_result finalgrade1_ cross join tb_class_discipline classdisci2_ "
                + " where finalgrade1_.id_class_discipline=classdisci2_.id and finalgrade1_.id_student= :studentId and classdisci2_.id_class= :clazzId ) as tmp )",
        new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));


text:
Q: Effect of shape on memory allocation by tensorflow on GPU When I create a variable with shape (L, N, N) on a nvidia GPU with tensorflow, does the variable occupies a tiling of L square pieces where each piece is N x N?
For example, three square chunk of memories tiled together would be:
# --- #
| NxN |
# --- #
| NxN |
# --- #
| NxN |
# --- #

How would tensorflow allocate GPU memory for a variable with a shape of (a, b, N, N)?

A: Memory on the GPU is allocated as a 1-dimensional array of bytes, with alignment if possible. In your example, the tensor with shape (L, N, N) will be a 1-D array of size 8*L*N*N bytes; the (a, b, N, N) case will be 8*a*b*N*N bytes, assuming float64 values.
You can find this out by reading the TensorFlow source code:

*

*gpu_cudamalloc_allocator.h declares the GPUcudaMallocAllocator class with void* AllocateRaw(size_t alignment, size_t num_bytes), implemented in

*gpu_cudamalloc_allocator.cc.

*allocator.h declares the Allocator class, parent of GPUcudaMallocAllocator, which declares void* AllocateRaw(size_t alignment, size_t num_bytes).

Since these AllocateRaw functions take a single size, all TensorFlow memory is allocated in 1-D arrays under the hood. This is common in practice, since it's easy to map higher-order array representations onto a contiguous 1-D block of memory, and it maximizes throughput for transfers onto the device and back.


text:
Q: Can I prevent the CLR from optimizing away debugging information? I've written an abstract base class for unit tests that sets up just enough environment for our tests to run. The class exposes some of the runtime environment bits as properties whose types vary test by test (the property types are type arguments specified in the inheriting, concrete test class).
This is all well and good, except a co-worker noticed that he can't view any of the class' properties in the debugger. Turns out the reason is that he had no fields defined in his inheriting class, and the CLR optimized something or other away, so the debugger couldn't display the properties. Is it possible to prevent this in the base class somehow, or do I have to resort to telling everyone they need to define at least one field which is used somewhere during the tests?
Edit:
Sounds like a likely culprit should be the optimization/debug settings. That said, I'm building the app from Visual Studio in Debug mode, I've double-checked that all projects are set for a debug build, and none of the projects in this solution have the Optimize flag set.
Perhaps it would also be relevant to note that I'm using MSTest and the Visual Studio test runner.
Edit 2:
By "can't view properties" I'm referring to when I evaluate the property in Quickwatch and get a red exclamation mark and a text "Could not evaluate expression" error text. And lest you think I'm entirely off base with my suspicions, adding an instance field that gets initialized in the test initialize method makes the problem go away...
Edit 3:
Checked the build output. I notice that the compiler is invoked with these options:
/debug+
/debug:full
/optimize-
/define:DEBUG,TRACE

I should think that would be enough to stop this from happening, but there you go. :)

A: I've encountered this same problem before, and it's invariably due to the fact that Debug mode has been turned off in some way. Try checking each of the following:

*

*The current build configuration for the solution and the appropiate project(s) is Debug.

*In the Build tab of the property pages, the Optimize code checkbox is unchecked.

If this is all correct, then I recommend you paste the text written to the Output window here so can we can potentially spot any more unusual cause of the issue.

A:
Make sure your arent trying to debug your release build.
All of these compile settings set behind these configurations.
The debug version is one for debugging ;-)

A: In my case, the project configuration was correct, but my code was the result of a decompilation from ILSpy, and it had assembly attributes like the following:
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]

Removing these attributes fixed the debugger...


text:
Q: Fgets from the file until end of line I tried using mygets function so that the fgets will only read one line:
void * mygets(char *name, int len, FILE * stream)
{
    fgets(name,len,stream);

    if (name[strlen(name) - 1] == 10)
    {
        name[strlen(name) - 1] = 0;
    }
}

And the file content is:
John Smith //Name

19 // Age

175.62 // Height

87  // Weight

Using single linked-list, I just wanted the *mygets to read only until John Smith then store it to a typedef struct named client by:
typedef struct nodebase{
    char name[40]; //Just in case, the client's name can be long
    int age;
    double height;
    int weight;
    struct nodebase *next;
    }listnode;

int main()
{
listnode *head;
listnode *tail;
listnode *client;
FILE *f;

f=fopen("filename.txt","r");

while(!feof(filename))
{
    client = malloc(sizeof(listnode));
    mygets(client->name,40,filename);

    if (head == NULL)
    {
        head = client;
    }
    else
    {
        tail->next=client;
    }
    tail = client;
    client =head;
}

while(client!=NULL)
{
    printf("\n%s\n",&client->name);
    client = client->next;
}

}

But the problem is, the program prints the entire file (including the age, height, and weight).
I cannot find anything wrong with my *mygets.
***I am using Tiny C on Windows

A: You have lots of typos and mistakes in the code you have posted in your question.

*

*FILE *f declaration doesn't end with semicolon;

*Condition in while(client!NULL) is not valid C condition, it should be != there;

*head and tail did not declared.

I hope that by the way you have working version of this code.
What is about your question, the code just works as it is written - your mygets function reads a line from the file, so in your while(!feof(filename)) loop you read file contents line by line (name, age, height, weight) and put entries into the linked-list. Then you just print them by traversing linked list from beginning to the end.


text:
Q: Split cat() output into new lines with bullet points on rmarkdown I am creating an Rmarkdown report and I did like to list some items with bullet points, I have items inside cat function like this:
cat(
  "First Case Reported in : ","•",as.character(as.Date("2023-01-23")),
  "TB outbreak been ongoing for"," •",paste0(55,' ', 'Weeks'),
  "cummulative cases"," •",4567," ",
  "Total cases in last 24hrs"," •", 67)
)

I want to split this into separate lines  for easy visibility
I have tried sep="\n" but its giving wrong output:
cat(
  "First Case Reported in : ","•",as.character(as.Date("2023-01-23")),
  "TB outbreak been ongoing for"," •",paste0(55,' ', 'Weeks'),
  "cummulative cases"," •",4567," ",
  "Total cases in last 24hrs"," •", 67, sep="\n"
)

my Desired output
First Case Reported in :  • 2023-01-23
TB outbreak been ongoing for  • 55 Weeks
cummulative cases  • 4567
Total cases in last 24hrs  • 67

What is the clever way of nailing this on rmarkdown

A: If it has to be cat(), you can manually place those newlines (and remove separator as the default value, " ", messes with output alignment) :
```{r}
cat(
  "First Case Reported in : • ",as.character(as.Date("2023-01-23")),"\n",
  "TB outbreak been ongoing for • ",paste0(55,' ', 'Weeks'),"\n",
  "cummulative cases • ",4567," \n",
  "Total cases in last 24hrs • ", 67, "\n", sep = ""
)
```

Though your kintted output will look like this:

So why not inline code in your Markdown?
```{r include=FALSE}
obreak    <- 55
cases_c   <- 4567
cases_24h <- 67
```

First Case Reported in : • `r as.character(as.Date("2023-01-23"))`
TB outbreak been ongoing for • `r obreak` Weeks
cummulative cases • `r cases_c`
Total cases in last 24hrs • `r cases_24h`

Same on a screenshot to emphasize blocks and 2 spaces at the end of Markdown lines to introduce linebreaks in Markdown:

Resulting knit:


text:
Q: Shorten condition to check that x is not any of four numbers Is there any way to shorten the condition for this if statement?
int x;
if (x != 3 && x != 8 && x != 87 && x != 9){
  SomeStuff();
}

I'm thinking of something sort of like this:
if (x != 3, 8, 87, 9) {}

But I tried that and it doesn't work. Do I just have to write it all out the long way?

A: If you don't want to repeat this condition over and over, then use macro.
#include <iostream>

#define isTRUE(x, a, b, c, d)  ( x != a && x != b && x != c && x != d )

int main()
{
    int x(2);
    std::cout << isTRUE(x,3,8,87,9) << std::endl;

    if ( isTRUE(x,3,8,87,9) ){
        // SomeStuff();
    }
    return 0;
}

A: If you want to know if an integer is in a given set of integers, then use std::set:
std::set<int> accept { 1, 4, 6, 8, 255, 42 };
int x = 1;

if (!accept.count(x))
{
    // ...
}

A: Just for completeness, I'll offer up using a switch:
switch (x) {
    case 1:
    case 2:
    case 37:
    case 42:
        break;
    default:
        SomeStuff();
        break;
}

While this is pretty verbose, it only evaluates x once (if it is an expression) and probably generates the most efficient code of any solution.

A: If the numbers are not "1,2,3,4" and are, instead, a random number of random integers, then you could put those numbers in a data structure (such as an std::vector), and then iterate over that array using a loop (as suggested below, std::find is a ready-made option).
For example:
#include <algorithm>

int x;
std::vector<int> checknums;
// fill the vector with your numbers to check x against

if (std::find(checknums.begin(), checknums.end(), x) != checknums.end()){
    DoStuff();
}

A: int A[]={3, 8, 87, 9};

int x;

if (std::find(A, A+4, x)==A+4) SomeStuff();

A: Note that the use of macros is heavily frowned upon by many programmers of C++, since macros are very powerful and have the ability to be frustrating if created improperly. However, if created and used properly and intelligently they can be a major time saver. I don't see another way to get the requested syntax and code space per comparison similar to what you are requesting without compromising the efficiency, code space, or memory used by your program. Your goal was to have a shortcut, and most of the other solutions presented here are longer than what you originally wanted to shorten. Here are macros which will do so safely, assuming you are comparing an integer:
#pragma once
int unused;
#define IFNOTIN2(x, a, b) \
  if (unused = (x) && unused != (a) && unused != (b))
#define IFNOTIN3(x, a, b, c) \
  if (unused = (x) && unused != (a) && unused != (b) && unused != (c))
#define IFNOTIN4(x, a, b, c, d) \
  if (unused = (x) && unused != (a) && unused != (b) && unused != (c) && unused != (d))
#define IFNOTIN5(x, a, b, c, d, e) \
  if (unused = (x) && unused != (a) && unused != (b) && unused != (c) && unused != (d) && unused != (e))

Here is a working tested example with one of the above macros:
#include <iostream>
#include "macros.h"

int main () {
  std::cout << "Hello World\n";

  for (int i = 0; i < 100; i ++) {
    std::cout << i << ": ";
    IFNOTIN4 (i, 7, 17, 32, 87) {
      std::cout << "PASSED\n";
    } else {
      std::cout << "FAILED\n";
    }
  }
  std::cin.get();

  return 0;
}

Note that the macros should go in a header file that's included wherever you need to use them. Your code will fail to compile if you are already using a variable named 'unused' in your code elsewhere or trying to use these macros to compare something other than an integer. I'm sure you can expand the macros to handle other types of data if that becomes necessary.
Order of operations is preserved by using brackets around all inputs, and the value is saved to a variable before comparison to prevent multiple executions of CPU-intensive code.

A: Here is my solution using variadic template. The runtime performance is as efficient as manually writing x != 3 && x != 8 && x != 87 && x != 9.
template <class T, class U>
bool not_equal(const T& t, const U& u) {
  return t != u;
}

template <class T, class U, class... Vs>
bool not_equal(const T& t, const U& u, const Vs&... vs) {
  return t != u && not_equal(t, vs...);
}

int main() {
  std::cout << not_equal( 3, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal( 8, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal(87, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal( 9, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal(10, 3, 8, 87, 9) << std::endl;
}

Since C++17, the implementation can be simplified with the help of fold expressions:
template <class T, class... Vs>
bool not_equal(const T& t, const Vs&... vs) {
  return ((t != vs) && ...);
}

A: What about this:
#include <iostream>
#include <initializer_list>
#include <algorithm>

template <typename T>
bool in(const T t, const std::initializer_list<T> & l) {
    return std::find(l.begin(), l.end(), t) != l.end();
}

int main() {
  std::cout << !in(3, {3, 8, 87, 9}) << std::endl;
  std::cout << !in(87, {3, 8, 87, 9}) << std::endl;
  std::cout << !in(10, {3, 8, 87, 9}) << std::endl;
}

or overloading the operator!=:
template<typename T>
bool operator!=(const T t, const std::vector<T> & l) {
    return std::find(l.begin(), l.end(), t) == l.end();
}

int main() {
  std::cout << ( 3!=std::vector<int>{ 3, 8, 87, 9}) << std::endl;
  std::cout << ( 8!=std::vector<int>{ 3, 8, 87, 9}) << std::endl;
  std::cout << (10!=std::vector<int>{ 3, 8, 87, 9}) << std::endl;
}

Unfortunately at the moment parsers do not like to have initializer_list as argument of operators, so it is not possible to get rid of std::vector<int>  in the second solution.


text:
Q: jHtmlArea not working with jQuery 1.9.1 and above - What to do about it? I just found, that using jHtmlArea, the nice WYSIWYG text editor, does not work with the newer jQuery versions, from 1.9.1 and above.
I have taken most code from the example, but wanted to reference a current jQuery library.

    $(function () {
        $("textarea").htmlarea();
    });

    <textarea id="txtDefaultHtmlArea" cols="50" rows="15">

Test H3
This is some sample text to test out the WYSIWYG Control.

    </textarea>

I have created a fiddle. Unless I turn on the Migrate 1.1.0 script, the editor does not show the nicely formatted text area, just the bare HTML and the editor buttons do not work.
Here's how it currently looked like:

I also have reproduced this behavior with an asp.net WebForms page and with local files.
What can I do about it? Should I go and try to fix jHtmlArea for me? For other components on the page, I would like to use current jQuery. Will I get in trouble, when I reference both an old and newer jQuery version on the same page?
UPDATE: This has now been solved by the autor of jHtmlArea, according to this closed bug.

A: You can use jQuery migrate for backwards compatibility, and it will show you in the console what needs to be fixed to be up to date with jQuery 1.9+.
From the docs http://blog.jquery.com/2013/02/04/jquery-1-9-1-released/
Please, please, please, use the jQuery Migrate plugin and look at the upgrade guide if you're just
starting your upgrade to jQuery 1.9. The plugin will quickly find and fix any compatibility issues,
just look in the browser console. Once you fix the warnings you can remove it. Or, leave the plugin in
place until you have the chance to fix your code and plugins to make them 1.9-compatible.

A: It looks like they released a new version of JHtmlArea that fixed the problem.
https://jhtmlarea.codeplex.com/downloads/get/832017


text:
Q: Show alert and interact using UIKit in SwiftUI view I am new to SwiftUI so please excuse me if i am writing something wrong. I have a SwiftUI file. Inside this SwiftUI file i have the following code. I need help doing two things. How do i show the alert i created in UIKit at the center of the screen above the TestView? Second how can i tap 'edit profile' and call a function?
       import SwiftUI
        import UIKit

    public struct TestView: View {

            @State var show: Bool

        public var body: some View {
        Button{
        UIAlertViewPopup(show: $show, title: "test", message: "test")
              } label {
                 Text("tap me")
                  }
        }

        struct UIAlertViewPopup: UIViewControllerRepresentable {

            typealias UIViewControllerType = UIAlertController

            @Binding var show: Bool

            var title: String
            var message: String

            func makeUIViewController(context: UIViewControllerRepresentableContext<UIAlertViewPopup>) -> UIAlertController {

                let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

                let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) { (action) in
                    self.show = false
                }

                let submitAction = UIAlertAction(title: "Edit profile", style: .default) { (action) in
                    self.show = false
                }

                alert.addAction(cancelAction)
                alert.addAction(submitAction)

                return alert
            }

            func updateUIViewController(_ uiViewController: UIAlertController, context: UIViewControllerRepresentableContext<UIAlertViewPopup>) {

            }

            func makeCoordinator() -> UIAlertViewPopup.Coordinator {
                Coordinator(self)
            }

            class Coordinator: NSObject, UIAlertViewDelegate {

                var control: UIAlertViewPopup

                init(_ control: UIAlertViewPopup) {
                    self.control = control
                }

            }
        }
}

A: I believe you need to return your own custom UIViewController from makeUIViewController and then present the UIAlertController using that. In updateUIViewController you can use the value of @Binding var show: Bool to decide if to present/hide the alert. You also need to update its message and title (Note: I'm not sure if UIAlertController allows that after it has been shown in which case you'll have to hide and present again).
Also, your UIAlertViewPopup should be above or below the Button or part of its label, not in its action.
Here is a sample I made:
import SwiftUI
import UIKit

public struct UIAlertTest: View {

    @State var show: Bool = false
    @State var title = ""
    @State var message = ""

    public var body: some View {
        Button("Show"){
            title = "Title"
            message = "Message"
            show = true
        }
        .task(id: show) {
            if show {
                // test updating the alert 2 secs after it has been presented.
                do {
                    try await Task.sleep(for: .seconds(2))
                }catch {
                    return
                }
                title = "Updated Title"
                message = "Updated Message"

                // test programatically hiding the alert 2 + 3 = 5 seconds after it has been presented.
                do {
                    try await Task.sleep(for: .seconds(3))
                }
                catch{
                    return
                }
                show = false
            }
        }
        .background {
            UIAlertViewPopup(show: $show, title: title, message: message)
        }
    }

    struct UIAlertViewPopup: UIViewControllerRepresentable {

        @Binding var show: Bool

        var title: String
        var message: String

        func makeCoordinator() -> Coordinator {
            Coordinator()
        }

        func makeUIViewController(context: UIViewControllerRepresentableContext<UIAlertViewPopup>) -> UIViewController {
            context.coordinator.viewController
        }

        func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<UIAlertViewPopup>) {

            if show {
                if let alert = context.coordinator.alert {
                    // just update its properties if it is already showing
                    alert.title = title
                    alert.message = message
                }
                else {
                    // create an alert and present it
                    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
                    context.coordinator.alert = alert
                    uiViewController.present(alert, animated: true)
                }
                // update the didHide closure to use the new version of the binding in case it changed.
                context.coordinator.didHide = {
                    show = false
                }
            }
            else {
                // dismiss the alert if the binding was just changed.
                // if an alert button was tapped it will already be dismissed and be nil by now because it is a weak var.
                if let alert = context.coordinator.alert {
                    alert.dismiss(animated: true)
                }
            }
        }

        class Coordinator: NSObject {

            lazy var viewController: UIViewController = UIViewController()
            var didHide: (() -> Void)?

            weak var alert: UIAlertController? {
                didSet {
                    if let alert {
                        let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) { [weak self] action in
                            self?.didHide?()
                        }

                        let submitAction = UIAlertAction(title: "Edit profile", style: .default) { [weak self] action in
                            self?.didHide?()
                        }

                        alert.addAction(cancelAction)
                        alert.addAction(submitAction)
                    }
                }
            }
        }
    }
}


text:
Q: ls: Dereference symlink but retain color Hopefully as simple as it sounds. The problem with ls -alL is that it references the original file, so it no longer colors the output as a symlink.
Essentially, I just want to get rid of the link in the output - from the arrow onward e.g. .vimrc -> .dotfiles/vim/.vimrc
It's really just for sake of aesthetics. My alternative would be to find a way to group the symlinks, so I can turn this:
.tmux.conf -> .dotfiles/tmux/.tmux.conf
.tmuxinator -> .dotfiles/tmuxinator/.tmuxinator
.vim
.viminfo
.vimrc -> .dotfiles/vim/.vimrc
Folder

into this:
.vim
.viminfo
.tmux.conf -> .dotfiles/tmux/.tmux.conf
.tmuxinator -> .dotfiles/tmuxinator/.tmuxinator
.vimrc -> .dotfiles/vim/.vimrc
Folder

Any help would be much appreciated!

A: Try piping the output through a program like sed or perl and use the substitute regex to get rid of what you don't want like| perl -pe 's/(.*?)->.*/$1/'


text:
Q: Getting around only having one of the same pseudo elements I'm trying to create something like this

Here the ribbon in the middle is an image. And the gradients surrounding it should be made with CSS.
My goal for this is to have an element to be the title on a page and for this displayed under that title. The code being something like this.

This is a Title

So by adding that class to the h1, the image would be displayed underneath.
I was trying something like this.
    h1.page-title {
      display: block;
    }
    h1.page-title::after {
      content: url(./path/to/image);
      display: block;
    }

This did what I was trying to do by adding the image under but I don't know how to add the gradients since multiple pseudo after elements can't be added.
I would like to be able to do this with one HTML tag but I could also not figure this out with two tags. Any help is appreciated.
EDIT:
This is what I'm trying to get the end product to look like

A: With before and after pseudo elements we can turn a single DOM element into 3.
What you are going to want to do is set the background image on the h1 element itself and use your ::before and ::after pseudo elements for your lines.
Here is the CSS I came up with:
h1.page-title {
      position: relative;
  display: inline-block;
      background-image: url('https://media.istockphoto.com/photos/red-ribbon-picture-id473856462?k=6&m=473856462&s=612x612&w=0&h=VMdTIdIJCbQ8CjHmb90ywhRB561z_XKx09eI6qJXMF0=');
  background-repeat: no-repeat;
  background-position: 50%;
  text-align: center;
  left: 50%;
  transform: translateX(-50%);
    }
.page-title:before,
.page-title:after {
  content: "";
  position: absolute;
  height: 5px;
  border-bottom: 1px solid blue;
  top: 0;
  width: 300px;
}
.page-title:before {
  right: 100%;
  margin-right: 10px;
}
.page-title:after {
  left: 100%;
  margin-left: 10px;
}

Note: I did not do a gradient with the lines like your example, this is just a simple example to show you how to accomplish with a single div. You will need to adjust the CSS to suit.

A: I am referring this Site1 Site2
With the help of position: sticky;, z-index: 10; and hr tag i have coded below example,

<!DOCTYPE html>


text:
Q: LOAD DATA INFILE skipping records I'm trying to load data from a CSV file into a MySQL database, and noticed that a large number of records seem to be skipped when I import the file.
The data comes from a Government source, and is very oddly formatted with single quotes, etc in unusual places. Here's a sample of a record not getting inserted:
"'050441'","STANFORD HOSPITAL","CA","H_HSP_RATING_7_8","How do patients rate the hospital overall?","Patients who gave a rating of'7' or '8' (medium)","22","300 or more","37",""

This record, however, does get inserted:
"'050441'","STANFORD HOSPITAL","CA","H_HSP_RATING_0_6","How do patients rate the hospital overall?","Patients who gave a rating of '6' or lower (low)","8","300 or more","37",""

The SQL I'm using to load the data is here:
mysql> load data infile "c:\\HQI_HOSP_HCAHPS_MSR.csv" into table hospital_qualit
y_scores fields terminated by "," enclosed by '"' lines terminated by "\n" IGNOR
E 1 LINES;

Anyone have any ideas why this is happening? It seems that only have of the records are actually being inserted correctly.

A: After executing the query with failed record mentioned over here.
mysql> load data ....;

execute the foll code
mysql> show warnings;

It will show the error why the query got failed? and carry on with the next step to solve it.
I did a small test with ur data which worked fine:
CREATE TABLE `test2` (
  `id` int(11) NOT NULL,
  `no` varchar(20) NOT NULL,
  `name` varchar(20) NOT NULL,
  `country` varchar(20) NOT NULL,
  `rating` varchar(20) NOT NULL,
  `rate_desc1` varchar(100) NOT NULL,
  `rate_desc2` varchar(100) NOT NULL,
  `no1` int(11) NOT NULL,
  `desc3` varchar(20) NOT NULL,
  `no2` int(11) NOT NULL,
  `desc4` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

/var/lib/mysql/test/test.csv contianing both of working n non-working records:
1,"'050441'","STANFORD HOSPITAL","CA","H_HSP_RATING_7_8","How do patients rate the hospital overall?","Patients who gave a rating of'7' or '8' (medium)","22","300 or more","37",""
2,"'050441'","STANFORD HOSPITAL","CA","H_HSP_RATING_0_6","How do patients rate the hospital overall?","Patients who gave a rating of '6' or lower (low)","8","300 or more","37",""
mysql> load data infile "test.csv" into table test2 fields terminated by "," enclosed by '"' lines terminated by "\n" IGNORE 1 LINES;

result:
Query OK, 2 rows affected (0.05 sec)
Records: 2  Deleted: 0  Skipped: 0  Warnings: 0

Conclusion: So, i think the difference is only in the datatypes of the columns n see the warnings genereated


text:
Q: Apollo Link State Error - Error sending request to origin I get the following errors when signing up/signing into my mobile app using react native
> (node:1474) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): JsonWebTokenError: jwtmalformed
>
> ERRO[0166] Error sending request to origin. This likely means that the origin GraphQL server did not respond to theproxied request. To resolve this, verify the Origin specification in the Engine configuration matches the corresponding GraphQL server.  error="Post http://[::]:51865/graphql: net/http: request canceled (Client.Timeout exceeded while awaiting headers)" url="http://[::]:51865/graphql"

I isolated the error to my client state below. It likely occured due to my apollo link state query/mutation. After I remove my client state, my mobile app can sign up/sign in without problem. Once I put the client state codes back in, I get the above error again
Anyone with good grasp of react and apollo graphql can help advise where I went wrong. As the error report by apollo is rather vague (at this moment), hard for me to pin down where specifically did the error occur
const client = new ApolloClient({
  uri: "http://localhost:5000/graphql",
...
  clientState: {
    defaults: defaultState,
    resolvers: {
      Query: {
        getMeInfo: (_, d, { cache }) => {
          return defaultState.me;
        }
      },
      Mutation: {
        updateMeInfo: (_, { _id, email, firstName, lastName }, { cache }) => {
          // KIV
          console.log("CACHE", cache);
        },
        resetCurrentGame: (_, d, { cache }) => {
          cache.writeData({ data: defaultState });
          return defaultState.currentGame;
        },
        updateGame: (_, { index, value }, { cache }) => {
          const prevState = cache.readQuery({ query: CURRENT_GAME });
          const data = {
            currentGame: {
              ...prevState.currentGame,
              [index]: value
            }
          };
          cache.writeData({
            query: CURRENT_GAME,
            data
          });
          return data.currentGame;
        }
      }
    }
  },...


text:
Q: Why does a .bmp image have two types of file headers? I recently opened 2 identical bitmap images in Notepad++
The one header begins with:
'Bmb' and the other with: 'Bm~'
Why is that?

A: This is not the entire header - and actually it's one and a half field from the header.
Here's the header format from Wikipedia:

Offset dec
Size
Purpose

0
2 bytes
The header field used to identify the BMP and DIB file is 0x42 0x4D in hexadecimal, same as BM in ASCII. The following entries are possible:- BM - Windows 3.1x, 95, NT, ... etc.- BA - OS/2 struct bitmap array- CI - OS/2 struct color icon- CP - OS/2 const color pointer- IC - OS/2 struct icon- PT - OS/2 pointer

2
4 bytes
The size of the BMP file in bytes

6
2 bytes
Reserved; actual value depends on the application that creates the image, if created manually can be 0

8
2 bytes
Reserved; actual value depends on the application that creates the image, if created manually can be 0

10
4 bytes
The offset, i.e. starting address, of the byte where the bitmap image data (pixel array) can be found.

BM is the value of the first field. The third "character" is actually the first byte from the second field (size of the BMP in bytes) incorrectly interpreted as text.

A: Because the header is neither Bmb nor Bm~. It is BM. Your bitmaps were not identical after all.
This is specified in the BITMAPFILEHEADER structure: "The file type; must be BM."

A: In the Header, the first 2 Bytes must be "BM" which is what you got.
The next 4 Bytes store the size of the file , which , by co-incidence , in your case , looks like "P" or "~".
You can try to take the raw Bytes in the 4 locations & Calculate the file size. It should match the file size on Disk.
Alternately, use Image Tools to Process the Header & extract the file size & then compare.


text:
Q: Check if Email Address Belongs to Yahoo Yahoo blocks emails from our website. We've written them to reverse that decision without much luck. So we block site registrations from @yahoo.com emails. Our problem is Yahoo has other email domains besides @yahoo.com. For instance @ymail.com, @rocketmail.com, @btinternet.com, and I'm sure many more. Plus international domains.
So the question is, how do I check if an email domain belongs to Yahoo? I supposed I could try to find a definitive list of all Yahoo domains, but I'm sure there has to be a better way. For instance doing some kind of host lookup on the domain.
Are there any suggestions to do that in PHP?

A: Definitive list is probably the best way to go. You don't want to have to do some kind of lookup every time someone registers for your site. But if you really don't want to use a static list, you should be able to use getmxrr() and see if the MX record is from yahoo.

A: ymail.com and rocketmail.com both list yahoo.com as their DNS MX servers, so that's an obvious giveaway. btinternet.com, however, doesn't.
You can use getmxrr() to retrieve the MX list


text:
Q: Excel MATCH doesn't MATCH The following formula returns #N/A.
=MATCH(1,SUBTOTAL(2,OFFSET(U5,ROW(U5:U400)-ROW(U5),0)),0)

If I highlight "SUBTOTAL(2,OFFSET(U5,ROW(U5:U400)-ROW(U5),0))" and hit F9, I'd get an array of 0 and 1.
The question is: why doesn't MATCH find 1 in the array? As the matter of fact, MATCH doesn't find 0 either.


text:
Q: Запись из переменной в базу с другой формы value Всем пис.
Есть 2 формы и 2 сабмита.
<form id="1">
 <input id="1" name="alehsa-1" value="1"></input>
 <input id="1" name="alehsa-2" value="2"></input>
</form>

и
<form id="2">
 <input id="3" name="alehsa-3" value="3"></input>
 <input id="4" name="alehsa-4" value="4"></input>
</form>

При нажатии на сабмит формы 1 данные добавляются из инпута 1 и 2, а при нажатии на сабмит формы 2 данные 3 и 4 но нужно к ним добавить ещё данные из первой формы из инпута id-1. Как это всё провернуть ибо деревянный по уши. Заранее спасибо за готовое решение

A: Отправка данных одной копкой типа submit из разных форм невозможна.
Можно осуществить это другими способами:
Простое и дешёвое решение:
Сделайте всё одной формой. А в принимающем скрипте используйте те значения, которые требуется.
Сложное и дорогое решение:
Сделайте в формах скрытые поля, в которые через JS будете копировать пользовательский ввод.

A: По-быстрому можно сделать с помощью JavaScript и jQuery:
По событию submit любой из форм выполнить их сериализацию с помощью jQuery.serialize и с помощью служебного объекта JavaScript window.location перезагрузить страницу с параметрами форм.
Соответственно, если вам нужно перейти на другую страницу, адрес нужно указать перед знаком вопроса "?"
 <form id="f1" class="s-form">
  <input id="i1" name="alehsa-1" value="1">
  <input id="i2" name="alehsa-2" value="2">
  <input type="submit">
 </form>

 <form id="f2" class="s-form">
  <input id="i3" name="alehsa-3" value="3">
  <input id="i4" name="alehsa-4" value="4">
  <input type="submit">
 </form>

 <script src="http://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
 <script>
 jQuery('.s-form').submit(function () {
    window.location.search = "?" + jQuery(".s-form").serialize();
 });
 </script>

Помните что аттрибут "id" должен быть уникальным на странице. Этим он и отличается от аттрибута "class"


text:
Q: Симуляция медленной скорости загрузки (upload) на сервер Возникла задача потестить процесс загрузки файлов на сервер. Но на локальном сервере они загружаются за доли секунды, поэтому вопрос - как симулировать медленный коннект? Желательно малой кровью, по минимуму утилит и настроек. Система ubuntu 12.04, сервер apache2, браузер Chrome.
A: Nginx + upload module
Пример конфигурации есть по ссылке выше. Скорость закачки регулируется при помощи директивы upload_limit_rate.
A: Есть такая программка как Fiddler. Она умеет имитировать модемную скорость, а сама по себе очень маленькая и простая.


text:
Q: Forge Viewer - model derivative API - Error file conversion to SVF I am following the tutorial to upload a NWD file to view in a browser, and I'm using the following steps:

*

*Registered an APP

*Acquired Auth token

I am then using the Postman to send the request through APIs

*

*Authenticate with scope data:read data:write data:create bucket:read bucket:create to get the Access token  -   Successful

*Create Bucket – Successful

*Upload File – Successful

{
    "bucketKey": "test_27052918",
    "objectId": "urn:adsk.objects:os.object:qrailtest_27052918/Z2_07_85_FULL.nwd",
    "objectKey": "Z2_07_85_FULL.nwd",
    "sha1": "b25528317db44a06e39a3fa2314af11d21802def",
    "size": 28824,
    "contentType": "application/octet-stream",
    "location": "https://developer.api.autodesk.com/oss/v2/buckets/qrailtest_27052918/objects/Z2_07_85_FULL.nwd"
}

*Post Job SVF – successful

{
    "result": "success",
    "urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6cXJhaWx0ZXN0XzI3MDUyOTE4L1oyXzA3Xzg1X0ZVTEwubndk",
    "acceptedJobs": {
        "output": {
            "destination": {
                "region": "us"
            },
            "formats": [
                {
                    "type": "svf",
                    "views": [
                        "3d",
                        "2d"
                    ]
                }
            ]
        }
    }
}

*Check job status – Failed

{
    "type": "manifest",
    "hasThumbnail": "false",
    "status": "failed",
    "progress": "complete",
    "region": "US",
    "urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6cXJhaWx0ZXN0XzI3MDUyOTE4L1oyXzA3Xzg1X0ZVTEwubndk",
    "version": "1.0",
    "derivatives": [
        {
            "name": "LMV Bubble",
            "hasThumbnail": "false",
            "status": "failed",
            "progress": "complete",
            "messages": [
                {
                    "type": "error",
                    "message": "Translation failure",
                    "code": "TranslationWorker-InternalFailure"
                }
            ],
            "outputType": "svf"
        }
    ]
}

Is there anything that I'm missing here? Please suggest.

A: This case is processed via Forge Help since it contains private information from the requester. In our conversation, we found the job body in the Postman collection he provided is incorrect for an NWD file. The job config should have to change it into this one:
{
   "input": {
     "urn": "YOUR_URN"
   },
   "output": {
     "formats": [
       {
         "type": "svf",
         "views": [
           "2d",
           "3d"
         ]
       }
     ]
   }
 }

Note:
Before triggering a new job, the failed translation result should be deleted via calling DELETE :urn/manifest or pass x-ads-force: true in to request header of the API POST job call. Otherwise, the translation result will remain the old one, the failed one in this case.


text:
Q: Installation of Memcache and Memcached There are a lot of tutorials about how to install memcache(d). I managed to do it.
Used this to create an object, everything is working fine
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

But when I try with "new Memcached"
$memcache = new Memcached;
$memcache->connect('localhost', 11211) or die ("Could not connect");

There is an error:
Fatal error: Class 'Memcached' not found

I have php_memcache.dll in php directory and configuration goes:
extension=php_memcache.dll
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211

But what about memcached. Laravel is using it and I cannot cache anything using memcache because of that error.

A: You need to install memcached library, "Memcache"  and "Memcached" are 2 separate libraries, you have to install them from pecl https://pecl.php.net/package/memcached
https://pecl.php.net/package/memcache
when you have both their libraries, the y will be available for you to use.


text:
Q: this.props.navigation.navigate() is not working for AppDrawerNavigator I'm facing issue in navigation in android app. When button is clicked app screen freezes, it does not redirect to next screen which is createDrawerNavigator() screen. Calling it from the Country selection screen.
import React, { Component } from "react";
import { View, Image, StyleSheet } from "react-native";
import AsyncStorage from "@react-native-community/async-storage";
import {
  createSwitchNavigator,
  createStackNavigator,
  createDrawerNavigator,
  createAppContainer
} from "react-navigation";
import CustomizedStatusBar from "./src/components/CustomizedStatusBar";
import Splash from "./src/screens/Splash";
import Login from "./src/screens/Login";
import CountrySelection from "./src/screens/CountrySelection";
import Dashboard from "./src/screens/Dashboard";
import ImportantNotice from "./src/screens/ImportantNotice";
import ApplicationForm from "./src/screens/ApplicationForm";
import ApplicationForm2 from "./src/screens/ApplicationForm2";
import ApplicationForm3 from "./src/screens/ApplicationForm3";
import ApplicationForm4 from "./src/screens/ApplicationForm4";
import Instructions from "./src/screens/Instructions";
import TravelHistory from "./src/screens/TravelHistory";
import TravelHistoryDetails from "./src/screens/TravelHistoryDetails";
import DownloadStamp from "./src/screens/DownloadStamp";
import LearnAbout from "./src/screens/LearnAbout";
import Advices from "./src/screens/Advices";
import TellAFriend from "./src/screens/TellAFriend";
import Contact from "./src/screens/Contact";
import SideMenu from "./src/screens/SideMenu";
import SignatureCapture from "./src/screens/SignatureCapture";
import CMS from "./src/screens/CMS";
import GLOBAL from "./src/config/constants";
import { Provider } from "react-redux";
import store from "./src/redux/store/index";
import NavigationDrawerStructure from "./src/components/NavigationDrawerStructure";
import NavigationService from "./src/config/NavigationService";

const CMSStackNavigator = createStackNavigator({
  CMS: {
    screen: CMS
  }
});

const HomeStackNavigator = createStackNavigator({
  Home: {
    screen: Dashboard
  }
});

const ApplicationFormStackNavigator = createStackNavigator({
  ApplicationForm: {
    screen: ApplicationForm,
    navigationOptions: ({ navigation }) => ({
      title: "",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const ApplicationForm2StackNavigator = createStackNavigator({
  ApplicationForm2: {
    screen: ApplicationForm2,
    navigationOptions: ({ navigation }) => ({
      title: "",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const ApplicationForm3StackNavigator = createStackNavigator({
  ApplicationForm3: {
    screen: ApplicationForm3,
    navigationOptions: ({ navigation }) => ({
      title: "",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const SignatureCaptureStackNavigator = createStackNavigator({
  SignatureCapture: {
    screen: SignatureCapture,
    navigationOptions: ({ navigation }) => ({
      title: "",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const ApplicationForm4StackNavigator = createStackNavigator({
  ApplicationForm4: {
    screen: ApplicationForm4,
    navigationOptions: ({ navigation }) => ({
      title: "",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const TravelHistoryStackNavigator = createStackNavigator({
  TravelHistory: {
    screen: TravelHistory
  }
});

const TravelHistoryDetailsStackNavigator = createStackNavigator({
  TravelHistoryDetails: {
    screen: TravelHistoryDetails
  }
});

const DownloadStampStackNavigator = createStackNavigator({
  DownloadStamp: {
    screen: DownloadStamp,
    navigationOptions: ({ navigation }) => ({
      title: "IMMIGRATION STAMP",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const TellAFriendStackNavigator = createStackNavigator({
  TellAfriend: {
    screen: TellAFriend,
    navigationOptions: ({ navigation }) => ({
      title: "TELL A FRIEND",
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
      },
      headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
    })
  }
});

const AppDrawerNavigator = createDrawerNavigator(
  {
    home: {
      screen: HomeStackNavigator
    },
    application_form: {
      screen: ApplicationFormStackNavigator,
      navigationOptions: {
        drawerLabel: "",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    application_form2: {
      screen: ApplicationForm2StackNavigator,
      navigationOptions: {
        drawerLabel: "",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    application_form3: {
      screen: ApplicationForm3StackNavigator,
      navigationOptions: {
        drawerLabel: "",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    signature_capture: {
      screen: SignatureCaptureStackNavigator,
      navigationOptions: {
        drawerLabel: "",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    application_form4: {
      screen: ApplicationForm4StackNavigator,
      navigationOptions: {
        drawerLabel: "",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    travel_history: {
      screen: TravelHistoryStackNavigator
    },
    travel_history_details: { screen: TravelHistoryDetailsStackNavigator },
    download_stamp: {
      screen: DownloadStampStackNavigator,
      navigationOptions: {
        drawerLabel: "IMMIGRATION STAMP",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    tellafriend: {
      screen: TellAFriendStackNavigator,
      navigationOptions: {
        drawerLabel: "TELL A FRIEND",
        drawerIcon: ({ tintColot }) => (
          <Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
        )
      }
    },
    cms: {
      screen: CMSStackNavigator
    }
  },
  {
    contentComponent: SideMenu
  }
);

export default class App extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {}

  componentDidMount() {}

  getPreferenceInfo = async () => {
    const isLoggedIn = await AsyncStorage.getItem(
      GLOBAL.PREFERENCE_STORAGE_KEY.IS_LOGGED_IN
    );
    const isLanguageSelected = await AsyncStorage.getItem(
      GLOBAL.PREFERENCE_STORAGE_KEY.IS_LANGUAGE_SELECTED
    );

    return { isLoggedIn: isLoggedIn, isLanguageSelected: isLanguageSelected };
  };

  render() {
    const AppSwitchNavigator = createSwitchNavigator(
      {
        SplashScreen: { screen: Splash },
        LoginScreen: { screen: Login },
        CountryScreen: { screen: CountrySelection },
        DashboardScreen: { screen: AppDrawerNavigator }
      },
      {
        initialRouteName: "AppScreen"
      }
    );
    const AppContainer = createAppContainer(AppSwitchNavigator);

    return (
      <Provider store={store}>
        <View style={{ flex: 1 }}>
          <CustomizedStatusBar />
          <AppContainer />
        </View>
      </Provider>
    );
  }
}

const styles = StyleSheet.create({
  bg: {
    width: "100%",
    height: "100%"
  }
});

// Calling it from CountrySelection.js (CountryScreen)

import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  Keyboard,
  TouchableWithoutFeedback,
  TouchableOpacity,
  SafeAreaView,
  KeyboardAvoidingView,
  ActivityIndicator,
  Alert
} from "react-native";
import AsyncStorage from "@react-native-community/async-storage";
import { StackActions, NavigationActions } from "react-navigation";
import CustomInputBox from "../components/CustomInputBox";
import GLOBAL from "../config/constants";
import { connect } from "react-redux";
import {
  selectCountryWithIndex,
  openCountrySelectionView,
  getCountries,
  openLanguageSelectionView
} from "../redux/actions/index";
import CountrySelectionPicker from "../components/CountrySelectionPicker";
import LanguageSelectionPicker from "../components/LanguageSelectionPicker";

class CountrySelection extends Component {
  constructor(props) {
    super(props);

    this.didPressSubmit = this.didPressSubmit.bind(this);
    this.navigateAfterFinish = this.navigateAfterFinish.bind(this);

    this.state = {
      isLoading: true,
      animating: false,
      selectedCountry: null,
      stores: []
    };
  }

  static navigationOptions = {
    header: null
  };

  navigateAfterFinish = screen => {
    const resetAction = StackActions.reset({
      actions: [NavigationActions.navigate({ routeName: "DashboardScreen" })]
    });

    this.props.navigation.dispatch(resetAction);
  };

  getSelectedCountryInfo = async () => {
    try {
      let value = await AsyncStorage.getItem(
        GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY
      );
      let selectedIndex = await AsyncStorage.getItem(
        GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY_INDEX
      );
      return { selectedCountry: value, selectedIndex: selectedIndex };
    } catch (e) {
      console.log(e);
    }
  };

  onSelectLanguage = async (langCode, langId) => {
    // Alert.alert(
    //   "Error",
    //   langCode + "==" + langId,
    //   [
    //     {
    //       text: "OK"
    //     }
    //   ],
    //   { cancelable: false }
    // );
    try {
      await AsyncStorage.setItem(
        GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY,
        JSON.stringify(this.props.countrySelectionReducers.selectedCountry)
      );
      await AsyncStorage.setItem(
        GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY_LANGUAGE_CODE,
        langCode
      );
      await AsyncStorage.setItem(
        GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY_LANGUAGE_CODE_ID,
        langId
      );
      await AsyncStorage.setItem(
        GLOBAL.PREFERENCE_STORAGE_KEY.IS_LANGUAGE_SELECTED,
        "true"
      );

      return true;
    } catch (e) {
      // Alert.alert(
      //   "Error",
      //   e,
      //   [
      //     {
      //       text: "OK"
      //     }
      //   ],
      //   { cancelable: false }
      // );
      console.log(e);
      return false;
    }
  };

  getAllDatas = () => {
    AsyncStorage.getAllKeys((err, keys) => {
      AsyncStorage.multiGet(keys, (err, stores) => {
        this.setState({ stores });
      });
    });
  };

  didPressSubmit = () => {
    this.props.navigation.navigate("DashboardScreen");
  };

  componentWillMount() {}

  componentDidMount() {
    this.props.getCountries();
    this.getAllDatas();

    // this.getSelectedCountryInfo().then(data => {
    //   this.props.selectCountryWithIndex(
    //     JSON.parse(data.selectedCountry),
    //     parseInt(data.selectedIndex)
    //   );
    // });
  }

  render() {
    const { navigate } = this.props.navigation;
    return (
      <KeyboardAvoidingView behavior={"padding"} style={{ flex: 1 }}>
        <View style={{ flex: 1 }}>
          <SafeAreaView style={{ flex: 1 }}>
            <TouchableWithoutFeedback
              onPress={Keyboard.dismiss}
              accessible={false}
            >
              <View style={styles.container}>
                <Image style={styles.bg} source={GLOBAL.LOGIN_BGIMG} />
                <View style={styles.formContainer}>
                  <Text style={styles.textContainer}>
                    {GLOBAL.SELECT_COUNTRY}
                  </Text>
                  <View style={{ flex: 1 }}>
                    <CustomInputBox
                      icon={
                        this.props.countrySelectionReducers.selectedCountry !==
                        null
                          ? {
                              uri: this.props.countrySelectionReducers
                                .selectedCountry.country_logo
                            }
                          : null
                      }
                      leftInputIconStyle={
                        this.props.countrySelectionReducers.selectedCountry !==
                        null
                          ? {
                              width: 32,
                              height: 20,
                              borderWidth: 0.5,
                              borderColor: "#c6c6c6"
                            }
                          : null
                      }
                      keyboardType="default"
                      returnKeyType="next"
                      showPlaceholder={false}
                      _placeholder={GLOBAL.COUNTRY_PLACEHOLDER}
                      showRightIcon={true}
                      rightIcon={GLOBAL.COUNTRY_RIGHT_ICON}
                      defaultValue={
                        this.props.countrySelectionReducers.selectedCountry !==
                        null
                          ? this.props.countrySelectionReducers.selectedCountry
                              .country_name
                          : null
                      }
                    />
                    <TouchableOpacity
                      style={{
                        backgroundColor: "transparent",
                        top: 0,
                        bottom: 0,
                        left: 0,
                        right: 0,
                        position: "absolute"
                      }}
                      onPress={() => this.props.openCountrySelectionView()}
                    />
                  </View>
                  <View style={{ flex: 1 }}>
                    <CustomInputBox
                      icon={
                        this.props.countrySelectionReducers.selectedLanguage !==
                        null
                          ? {
                              uri:
                                GLOBAL.URL.uploads +
                                this.props.countrySelectionReducers
                                  .selectedLanguage.language_code +
                                ".png"
                            }
                          : null
                      }
                      leftInputIconStyle={
                        this.props.countrySelectionReducers.selectedLanguage !==
                        null
                          ? {
                              width: 32,
                              height: 20,
                              borderWidth: 0,
                              borderColor: "#c6c6c6"
                            }
                          : null
                      }
                      keyboardType="default"
                      returnKeyType="done"
                      showPlaceholder={false}
                      _placeholder={GLOBAL.LANGUAGE_PLACEHOLDER}
                      showRightIcon={true}
                      rightIcon={GLOBAL.COUNTRY_RIGHT_ICON}
                      customStyle={{ marginTop: 20 }}
                      defaultValue={
                        this.props.countrySelectionReducers.selectedLanguage !==
                        null
                          ? this.props.countrySelectionReducers.selectedLanguage
                              .language_name
                          : null
                      }
                    />
                    <TouchableOpacity
                      style={{
                        backgroundColor: "transparent",
                        top: 0,
                        bottom: 0,
                        left: 0,
                        right: 0,
                        position: "absolute"
                      }}
                      onPress={() => this.props.openLanguageSelectionView()}
                    />
                  </View>
                  <TouchableOpacity
                    style={[styles.btn, { marginTop: 30 }]}
                    onPress={() => this.didPressSubmit()}
                  >
                    <Image
                      style={styles.btnImg}
                      resizeMode="contain"
                      source={GLOBAL.BTN_BGIMG}
                    />
                    <View style={styles.btnContainer}>
                      <Text style={styles.btnText}>{GLOBAL.LOGINBTN}</Text>
                    </View>
                  </TouchableOpacity>
                </View>
                {this.props.countrySelectionReducers.isAnimating ? (
                  <View
                    style={{
                      width: "100%",
                      height: "100%",
                      position: "absolute",
                      justifyContent: "center",
                      alignItems: "center"
                    }}
                  >
                    <View
                      style={{
                        flex: 1,
                        backgroundColor: "#000000",
                        width: "100%",
                        height: "100%"
                      }}
                      opacity={0.6}
                    />
                    <ActivityIndicator
                      style={{ alignSelf: "center", position: "absolute" }}
                      size="large"
                      color="#ffffff"
                    />
                  </View>
                ) : null}
              </View>
            </TouchableWithoutFeedback>
            <CountrySelectionPicker />
            <LanguageSelectionPicker />
          </SafeAreaView>
        </View>
      </KeyboardAvoidingView>
    );
  }
}

const mapStateToProps = state => {
  return {
    countrySelectionReducers: state.CountrySelectionReducers
  };
};

export default connect(
  mapStateToProps,
  {
    selectCountryWithIndex,
    openCountrySelectionView,
    getCountries,
    openLanguageSelectionView
  }
)(CountrySelection);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  bg: {
    width: "100%",
    height: "100%"
  },
  formContainer: {
    position: "absolute",
    width: "100%",
    paddingHorizontal: 30,
    flexGrow: 1
  },
  textContainer: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#ffffff",
    alignSelf: "center",
    textAlign: "center",
    marginBottom: 30
  },
  btn: {
    alignItems: "center",
    justifyContent: "center"
  },
  btnText: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#ffffff",
    alignSelf: "center"
  },
  btnContainer: {
    alignItems: "center",
    justifyContent: "center",
    position: "absolute"
  },
  btnImg: {
    resizeMode: "contain",
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    height: 46
  }
});

Wanted to redirect user to DashboardScreen from CountryScreen using this.props.navigation.navigate("DashboardScreen"). But it fails. No error is thrown.

A: This has been resolved. The issue was with hybrid-crypto-js library. It was throwing an exception due to which navigation stops.


text:
Q: SP Online : Subsite settings On my main site example.sharepoint.com I can add webparts and save it like a template but on a subsite example.sharepoint.com/sites/project1 I dont have neither of those options. In admin center I have allowed scripting.

A: If I am not mistaken, what you are referring to is the Galleries section of the site settings where "Web parts" and "List templates" are options. These options are only available at the root of the site collection because that is were list templates and web parts are stored.
You can still save list templates from a subsite, but to upload them for use on a site collection (including the subsite), you must navigate to the root of the site collection, go to Web parts or List templates, and upload them there. Than if you navigate back to the subsite, you will see they can now be used.


text:
Q: LINQ получить проблемный элемент Можно ли в LINQ получить элемент на котором свалилось выполнение запроса?
Ну скажем, я запускаю арифметическую операцию и не с того не с сего происходит деление на 0.
Могу я как-то посмотреть на него в режиме отладки?


text:
Q: Is ember.js stable enough to use in a real world project? I read that there api is unstable and might break. Just wanted to know if, as of today, the api is stable enough to be used.

A: There's a lot of projects based on Ember.js - so if you're worried about actually being able to get something done I think your fear is unwarranted. Check out their demo page.
Discourse, some very large discussion software, is written on top of Ember.js. Ultimately, you won't know if the API is good enough until you try it yourself but larger sites have shipped products on the platform.

A: Of course!
Check this podcast which is an interview with Yehuda Katz (one of the creators of ember.js) that was recorde not long ago, it will give you some insight. Ember.js is about to reach 1.0, so again, yes you can use it for real world projects, and many people are alredy doing it so you will not be alone.
Hope it helps.

A: I have build a application using the version 1.0.pre. Very old, but worked without problems to me. So in my opinion ember is very stable. After each release, the changes are blogged in http://emberjs.com/blog/, so you can update your app, if needed. Just ember-data have warnings about your usage, so if you want to use it, be aware.


text:
Q: How to use private dns zone which will be used when we access our website from our client vm in azure.How to configure dns zone for client virtual I configured the private DNS zone so that the client Virtual machine( which I created in it) can connect to the webserver( Which I created in Azure with loadbalancer ).I also did the network peering between vnet 1 and vnet2 which are private. vnet 1 is for webserver 1 and webserver2( I created this virtual machine and did virtual peering with webserver1).
After login to client I am trying to reach website mst300-lb.harmandeep14.com
mst300lb is my load balancer name
harmandeepkaur14.com is my privated dns zone name
I created the  feature iis in webserver 1 and webserver2
I want to reach  mst300-lb.harmandeep14.com in client but I cannot
where I am going wrong?
enter image description here
What should I do view this website on client virtual machine.
enter image description here
This is load ip address.
and that's the record I created in loadbalancer.
enter image description here

A: •   From what you have configured the environment, I can understand that you have configured the two webservers in the same virtual network, i.e., VNET1 and the client VM from where you are accessing the IIS webpage hosted on the webservers is hosted in virtual network 2, i.e., VNET2 and you have configured peering between them so that the client VM can access the IIS webpage hosted on the webserver pool configured as a backend in the load balancer.
Thus, you will have to create a CNAME record in your private DNS zone for the load balancer name with the alias as the actual name of the IIS webpage/website hosted on the servers as shown below in the snapshot: -

•   Once you create a CNAME record for the IIS webpage in your private DNS zone with the alias as the FQDN of the load balancer, ensure that an 'A' host record also exists for the load balancer such that the CNAME record can track and resolve the load balancer from here itself. Also do ensure that you have configured virtual network links with both the virtual networks as shown below in the snapshot for webservers and client VMs to be added in here.
Since, you are using private DNS zone, I would also recommend you create 'A' host records for both the webservers as well as client VMs, this will ensure that for your private network, every resource is registered in the appropriate DNS zone and the request for accessing the webpage is routed correctly to the backend resources. Also, ensure that the webpage/website application hosted on the webservers also have an 'A' host record in the private DNS zone created which will in effect load balance the traffic received on the frontend to the backend webservers and the webpages/websites hosted on them.

Also, do ensure that the website if hosted internally on port 80 TCP HTTP, then ensure that the health probe is configured accordingly in the load balancer rules for the traffic over HTTP port 80 to be routed and load balanced further to the backend pools.


text:
Q: how to translate only selected XML element using XSL transformer I am having a XML with custom namespace. I want to write XSTL to transform this input XML to output XML by converting selected element under the namespace other elements remains same in output XML
Example
<xml version="1.0">

    <abc:A>
        Books
    </abc:A>

I want to transform this XML to
<xml version="1.0">

    <sample>
        Book
    </sample>

How to write XSTL for this transformation?

A: consider the following input XML:
<?xml version="1.0" encoding="UTF-8"?>

    <abc:A>
        Books
    </abc:A>
    <abc:B>just another element</abc:B>

when this stylesheet is applied:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:abc="http://abc.en.com/abc">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="abc:A">
        <sample>
            <xsl:apply-templates/>
        </sample>
    </xsl:template>

</xsl:stylesheet>

the output is:

   <sample>

      Books

   </sample>

   <abc:B>just another element</abc:B>


text:
Q: Nested Json not detected I'm trying to parse a nested JSON through a REST Api but somehow it is not getting read. For example: I'm passing a JSON like this in my request body.
[
{
"first":"I like sfdc",
"second":"You like sfdc",
"third": "I want an apple",
"fourth": [
           { "ISDETAIL":false,
            "SERIAL":"X62348052228",
            "TYPE":"NEWKING",
            "STATE":"DKS"
            }
          ]
}
]

I am getting the rest response through
String jsonString = req.requestBody.toString();

This jsonString returns all the value in debug.
I try to write a wrapper class for the main json response like
global with sharing class RestWrapperELH {

    global class JSONRestResponse{
        global String first;
        global String second;
        global String third;
        global JSON fourth;
    }
}

And then I'm deserializing the json using this code
List<RestWrapperELH.JSONRestResponse> restPayload = (List<RestWrapperELH.JSONRestResponse>)JSON.deserialize(jsonString, List<RestWrapperELH.JSONRestResponse>.class);

But on debugging the restPayload, I'm getting a output like
21:19:28:014 USER_DEBUG [24]|DEBUG|(JSONRestResponse:[first=I like sfdc, second=You like sfdc, fourth=JSON:[], third=I want an apple])

I understand that I have to deserialize the nested JSON, I have tried writing a wrapper class around it using https://json2apex.herokuapp.com/ but I still can not work with it because the JSONRestResponse.fourth is always null.
What is it that I'm doing wrong ?

A: If you use https://json2apex.herokuapp.com/ this works fine.
The converted class is
public class JSON2Apex {

    public String first;
    public String second;
    public String third;
    public List<Fourth> fourth;

    public class Fourth {
        public Boolean ISDETAIL;
        public String SERIAL;
        public String TYPE;
        public String STATE;
    }

    public static List<JSON2Apex> parse(String json) {
        return (List<JSON2Apex>) System.JSON.deserialize(json, List<JSON2Apex>.class);
    }
}

Which easily shows the wrapper class when you try to pass your JSON.
System.debug(JSON2Apex.parse('[\n' +
        '{\n' +
        '"first":"I like sfdc",\n' +
        '"second":"You like sfdc",\n' +
        '"third": "I want an apple",\n' +
        '"fourth": [\n' +
        '           { "ISDETAIL":false,\n' +
        '            "SERIAL":"X62348052228",\n' +
        '            "TYPE":"NEWKING",\n' +
        '            "STATE":"DKS"\n' +
        '            }\n' +
        '          ]\n' +
        '}\n' +
        ']'));

Output as :
09:58:17.218 (233731852)|USER_DEBUG|[4]|DEBUG|(JSON2Apex:[first=I like sfdc, fourth=(Fourth:[ISDETAIL=false, SERIAL=X62348052228, STATE=DKS, TYPE=NEWKING]), second=You like sfdc, third=I want an apple])

Fourth as list.


text:
Q: Callback - after_save but NOT create How can you separate callbacks so that after_create runs one set of code, but !after_create, so to speak, runs another?

A: after_create After new object created
after_update After existing object updated
after_save Both creation and update

A: after_create callback for new object, after_update for persisted one.

A: You can have multiple callbacks which only execute based on conditions
model.rb
after_create :only_do_if_this
after_create :only_do_if_that

def only_do_if_this
  if do_this?
    # code...
  end
end

def only_do_if_that
  if do_that?
    # code...
  end
end

You can also add the condition to the callback itself
after_create :only_do_if_this, :if => proc { |m| m.do_this? }
after_create :only_do_if_that, :if => proc { |m| m.do_that? }

def only_do_if_this
  # code ...
end

def only_do_if_that
  # code...
end


text:
Q: querying years that contains multiple fields in oracle db i am trying to write a query in oracle db that helps me to select something that contains all 3 data, let me show an example
Say I have a table
ltr year
--------
'a' 2003
'b' 2003
'c' 2005
'a' 2003
'a' 2003
'j' 2008
'c' 2003

and I want to return the year(s) that contains at least one instance of the letters a, b, c. In here 2003 would be the only year that is returned.
So far I have
select distinct year
from Data
where letter = 'a' or letter = 'b' or letter = 'c';

This will return years 2005 as well which isnt correct..
What am I missing?
Any help is appreciated!

A: Specify the letter you want in your where clause and use having count(distinct ltr) = 3 to get all years that have all letters at least once.
select year
from data
where ltr in ('a','b','c')
group by year
having count(distinct ltr) = 3

if you want years that only have letters 'a', 'b', 'c':
select year
from data
group by year
having count(case when ltr not in ('a','b','c') then 1 end) = 0