text:
Q: Android Studio Gradle not using transitive dependencies Having experienced this problem in a separate project, I made a test project to verify the issue.

*

*Opening Android Studio 3.0, I created a new basic project.  Its main module was called app.

*I added a library module, called libraryone.

*In libraryone, I added a dependency to Gson, and added a single class with a single static method using Gson.

*In app, I added a dependency to libraryone.  I tested it plain, as well as with transitive = true, as the internet seemed to vaguely concur that doing so might help.  (It did not.)

*In app, in MainActivity, I used the class from libraryone.  This worked (as long as I didn't have transitive = false set, instead).

*However, I cannot reference Gson from MainActivity itself.  It gives a "Cannot resolve symbol 'Gson'" error, both from Android Studio, as well as from the command line Gradle.  This is...unusual and aggravating, as it means you have to repeat common dependencies all throughout a group of projects, and the classes are included in the output anyway.  Surely either I'm doing something wrong, or this is a bug?

My code is as follows:
MainActivity.java (in app)
package com.erhannis.test.dependencytest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.erhannis.test.libraryone.LibClass;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String s = LibClass.convert(new Object());
        System.out.println("out: " + s);

        new com.google.gson.Gson(); // This line gives a compile-time error: "Cannot resolve symbol 'Gson'"
    }
}

LibClass.java (in libraryone)
package com.erhannis.test.libraryone;

import com.google.gson.Gson;

public class LibClass {
    public static String convert(Object o) {
        Gson gson = new Gson();
        return gson.toJson(o);
    }
}

build.gradle (app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.erhannis.test.dependencytest"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation (project(path: ':libraryone'))
}

build.gradle (libraryone)
apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    defaultConfig {
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation 'com.google.code.gson:gson:2.8.2'
}

A: You are using:
implementation (project(path: ':libraryone'))
implementation 'com.google.code.gson:gson:2.8.2'

Check the official doc:

When your module configures an implementation dependency, it's letting Gradle know that the module does not want to leak the dependency to other modules at compile time. That is, the dependency is available to other modules only at runtime.

Here you can find a very good blog about it.

A: It is because you declared the transitive dependency as implementation. Use api instead of implementation change:
implementation 'com.google.code.gson:gson:2.8.2'

to:
api 'com.google.code.gson:gson:2.8.2'

The reason why you should declare the transitive dependency in your library can be found here

A: The best solution for this is to create a private Github/Gitlab repository for the aar dependency. You can also make it public if you want. The aar file does not contain transitive dependencies when used locally. We need to publish it somewhere with the .pom file. Here's how to do it,

*

*create a personal access token in Github

Github -> Settings -> Developer Settings -> Personal Access token - with write:packages / read:packages access level
(create two tokens if you need to distribute privately

*Add id 'maven-publish' to plugins in module level gradle

*Add the below code to module level gradle
task sourceJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    archiveClassifier.set("sources")
}

 publishing {
     publications {
         bar(MavenPublication) {
             groupId 'com.your'
             artifactId 'artifact'
             version '1.0'
             artifact sourceJar
             artifact("$buildDir/outputs/aar/YourLibraryName-release.aar")
             pom.withXml {
                 final dependenciesNode = asNode().appendNode('dependencies')
                 ext.addDependency = { Dependency dep, String scope ->
                     if (dep.group == null || dep.version == null || dep.name == null || dep.name == "unspecified")
                         return
                     final dependencyNode = dependenciesNode.appendNode('dependency')
                     dependencyNode.appendNode('groupId', dep.group)
                     dependencyNode.appendNode('artifactId', dep.name)
                     dependencyNode.appendNode('version', dep.version)
                     dependencyNode.appendNode('scope', scope)
                     if (!dep.transitive) {
                         final exclusionNode = dependencyNode.appendNode('exclusions').appendNode('exclusion')
                         exclusionNode.appendNode('groupId', '*')
                         exclusionNode.appendNode('artifactId', '*')
                     } else if (!dep.properties.excludeRules.empty) {
                         final exclusionNode = dependencyNode.appendNode('exclusions').appendNode('exclusion')
                         dep.properties.excludeRules.each { ExcludeRule rule ->
                             exclusionNode.appendNode('groupId', rule.group ?: '*')
                             exclusionNode.appendNode('artifactId', rule.module ?: '*')
                         }
                     }
                 }
                 configurations.compile.getDependencies().each { dep -> addDependency(dep, "compile") }
                 configurations.api.getDependencies().each { dep -> addDependency(dep, "compile") }
                 configurations.implementation.getDependencies().each { dep -> addDependency(dep, "runtime") }
             }
         }
     }

     repositories {
         maven {
             name = "GitHubPackages"
             url = uri("https://maven.pkg.github.com/GITHUB_USERID/REPOSITORY")
             credentials {
                 username = "GITHUB_USERID" // Better if you use env variable
                 password = "WRITE_ACCESS_TOKEN"
             }
         }
     }
 }

*In the Gradle toolbar you can find publish under the publishing subdirectory in your library module directory. ( Make sure to build the aar from build->build in module directory before publish)

*To use it in your project,  add following to your app level gradle file inside android{ }tag
 repositories {
     maven {
         name = "GitHubPackages"
         url = uri("https://maven.pkg.github.com/GITHUB_USERID/REPOSITORY")
         credentials {
             username = "GITHUB_USERID" // Better if you use env variable
             password = "READ_ACCESS_TOKEN"
         }
     }
 }

*Finally in dependencies
 implementation 'com.your:artifact:1.0'

*Gitlab is also pretty similar to this


text:
Q: Как лучше всего сделать отступы в моём случае?
У меня несколько вариантов:

*

*создать отдельный див и поместить туда весь контент (хедер, контент, футер и тд) для этого дива задать максимальную ширину к примеру 1170пх и margin: 0 auto; То есть так:

.width {
  max-width: 1170px;
  margin: 0 auto;
}

    <content></content>

*Либо для width прописать padding

*Для body прописать padding или margin (тут я тоже хз что лучше)
Подскажите как лучше всего это сделать? Мб 1,2 или 3 варианты?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a theory of structures different from Bourbaki's theory of structures? In Bourbaki's "Elements of Mathematics: Theory of sets", after an account of a set theory, a "theory of structures" is introduced. This book is difficult to read, but it seems, Bourbaki treat a structure as an object "defined" in set theory. Are there different approaches in defining what are structures?

A: General idea of a structure - the core aspect of a structure (as opposed to a theory) is to imply a concept of truth (e.g. using meta language or some internal concept) e.g. to assess whether or not the structure is a model of some theory.
Toposes as structures -
this said, topos theory can be regarded as an alternative approach to structures:
A topos is a certain type of nice (in a way set-like) category with a(n internal) truth concept (by something called a subobject classifier). Depending on the regarded topos, the truth concept given by its subobject classifier might look very different to the classical true/false and in general induces an intuitionistic logic to the category.
Toposes as alternative - category theory can be developed without reference to set theory, i.e. without a concept of membership relationship, see e.g. Category theory without sets (incl. references for further reading).


text:
Q: groupByKey vs hashPartitioner and mapPartitions? So, I have a data like the following,
[ (1, data1), (1, data2), (2, data3), (1, data4), (2, data5) ]

which I want to convert to the following, for further processing.
[ (1, [data1, data2, data4]), (2, [data3, data5]) ]

One way is to use groupByKey. Another way, is to partition the RDD according to the key using hashPartitioner, and then process the values for each key using mapPartitions. Which method would be more efficient?

A: I don't think you can use reduceByKey directly as recommended in the comments, but if you map the (Int, Object) pairs to (Int, List(Object)) then you can use it. I would expect the following to be among the most efficient methods however really practical tests are the best way to know which is best for your particular use case.
object main extends App {

  import org.apache.spark.{SparkContext, SparkConf}
  import org.apache.spark.rdd.PairRDDFunctions

  val conf = new SparkConf().setMaster("local").setAppName("example")
  val sc = new SparkContext(conf)

  val data = List((1, "data1"), (1, "data2"), (2, "data3"), (1, "data4"), (2, "data5"))

  val rdd = sc.parallelize(data).mapValues(str => List(str)).reduceByKey((l1, l2) => l1 ::: l2)
  rdd.collect().foreach{
    case (key, list) => println(s"key: $key values: ${list.mkString(";")}")
  }
  sc.stop()
}


text:
Q: How to set the degradation version for IE11 running in enterprise mode to something other than IE8? Our company is insistent on running I.E. 11 in enterprise mode to solve certain "security" issues, and as a result, is adding the intranet to the emulation list.
This intranet is currently running Bootstrap 3 and no longer works properly because of this.
Is there a way to tell I.E. 11 in enterprise mode to emulate I.E. 10 or I.E. 11 and not I.E. 8?

A: Enterprise Mode Forces page to render in Internet Explorer 8.
Enterprise mode is specifically designed for running Legacy applications on Internet Explorer 8.
If you want your page to render as IE 9 or 8 You can use below Meta Tag in the code.
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="X-UA-Compatible" content="IE=9" />

To force IE to use Latest Version of Internet Explorer use
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Ref
http://msdn.microsoft.com/en-us/library/windows/desktop/ff966528%28v=vs.85%29.aspx


text:
Q: lr_xml_get_value function fails I have this SOAP Response from testing with HP LoadRunner 12.53.  I need to extract a value can keep getting "No Matches were Found for the specific query" using the lr_xml_get_values function:
lr_xml_extract("XML={RESPONSE}",
       "XMLFragmentParam=OutputParam",
        "Query=/Envelope/Body/TimeExpenseAcknowledgmentCBM/RequestID/text()",
        LAST);

Here is my response:
"RESPONSE" =  "<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <timeexpresp:TimeExpenseAcknowledgmentCBM xmlns:timeexpresp="http://esoa.census.gov/soa/CanonicalModel/Core/CDM/TimeExpenseCDM/V1">
      <meta:RequestID xmlns:meta="http://esoa.census.gov/soa/CanonicalModel/Core/Common/V1">**N53e79c17.N60c0f9d8.7.15de03dae49.N3fbe**</meta:RequestID>
    </timeexpresp:TimeExpenseAcknowledgmentCBM>
  </soapenv:Body>
</soapenv:Envelope>"

I need to extract the RequestID value in **BOLD**  Any help??

A: This worked for me:
char * xml_input =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soapenv:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
 "<soapenv:Body>"
    "<timeexpresp:TimeExpenseAcknowledgmentCBM xmlns:timeexpresp=\"http://esoa.census.gov/soa/CanonicalModel/Core/CDM/TimeExpenseCDM/V1\">"
      "<meta:RequestID xmlns:meta=\"http://esoa.census.gov/soa/CanonicalModel/Core/Common/V1\">**N53e79c17.N60c0f9d8.7.15de03dae49.N3fbe**</meta:RequestID>"
    "</timeexpresp:TimeExpenseAcknowledgmentCBM>"
  "</soapenv:Body>"
"</soapenv:Envelope>";

Action() {

 int i, NumOfValues;
 char buf[64];

 lr_save_string(xml_input, "XML_Input_Param"); // Save input as parameter

 lr_xml_extract("XML={XML_Input_Param}",
      "XMLFragmentParam=Result",
      "Query=/Envelope/Body/TimeExpenseAcknowledgmentCBM/RequestID/text()", LAST );

 lr_output_message(lr_eval_string("Extracted: {Result}"));

 return 0;
}

Output:
Action.c(19): "lr_xml_extract" succeeded, 1 match processed
Action.c(23): Extracted: **N53e79c17.N60c0f9d8.7.15de03dae49.N3fbe**


text:
Q: What ways are there to work on a project in a testing environment where the Git commit needs to be different to the PHP code used for testing and dev? In my project the deployable version needs to have a copy of each of the external libs, a different config file and install and setup files, for security concerns, the main project is set to refuse to run if they are present. Thus the upstream copies of the other projects need to be committed to repo. How can I work on code running on localhost where the file layout and sometimes file contents from dev and testing are different to what I need to commit?
Background
I am working on a project on hosted on github and my main IDE is netbeans which has imperfect git support (good enough for >99% of my needs). The project is in PHP and uses several other projects as libraries.
As Netbeans does not have the best support for sub-repos I have chosen to keep each additional project in a separate project. This is fine as the central project looks at the config data for where to find these outside libs.
Half an answer
My instinct is to suppose that there will need to be some "build stage" prior to committing to the github repo but how on earth do I go about setting all that up?
I could write some sort of homebrew thing but then when I pull other people's contributions I would need to reverse the process unless we had a branch for builds and a branch for working copies which seems needlessly complex and could leave the dev(s) config data on public display (not to mention updates being a mess).
I have seen that others have wrestled with somewhat similar problems to no conclusion (at time of asking) (How to push and pull from github without sharing sensitive information? Smudge & clean?) so I am looking for anything that might help me come up with a solution

A:
my main IDE is netbeans which has imperfect git support

Most devs just use the command line. I switch to the NetBeans conflict resolver occasionally, which is very good, but for normal stuff the console is usually faster.

My instinct is to suppose that there will need to be some "build stage" prior to committing to the github repo
... unless we had a branch for builds and a branch for working copies

No, there is only ever one repository. It is better to think of your repo as your code history, rather than your deployment state. Branches should just be for features or large changes, which merge into your mainline/master.
There are a good deal of options available to you when deploying. The first is Composer, which Mark points out: when deploying you issue an install or update command, which fetches the dependencies that satisfy your library requirements recursively. You can use Bower to do the same thing for your JavaScript dependencies.
Some deployment strategies prefer to build locally and then scp/rsync to a remote server. Composer and Bower are still probably a good idea, but you write a build script (using Ant or Phing, for example) to create a build copy in a local temporary folder, and then send it to the server. It is common here also to push it to a new release folder on the server, and then swap a symlink or Apache config file when it's ready to go live.

the deployable version needs to have a copy of each of the external libs, a different config file and install and setup files, for security concerns

Assuming this is a web project, have you tried adding your sensitive environment data to your Apache configuration file? This can be trivially read in PHP, and of course PHP does not care that this information is different according to whether you are developing, testing, demoing a branch or operating live.

Further reading: an excellent PHP deployment book, free of charge, that suggests Phing and Capistrano.


text:
Q: error: unknown type name 'V' in C++ struct I checked other answers but they didn't work for me, I am getting error: unknown type name 'V' in my C++ code while using struct. I am unable to decipher why this error is occurring, please help.enter image description here

A: You are trying to execute statements at global scope.  C++ doesn't allow that.  You need to put your code inside a function.


text:
Q: Add a custom image to my digital clock as background im 100% new to coding and just started to follow some guides a few days ago. I am now making a digital clock for my desktop and i want to change my background to a custom image that i have.
Can someone explain to me where i can change it so that the background becomes my image that i have? BR
from tkinter import Tk
from tkinter import Label
import time
from PIL import Image, ImageTk

root = Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
root.attributes('-alpha', 1)
root.iconbitmap('klocka.ico (1).ico')
root.geometry('600x400+50+50')

window_width = 255
window_height = 50

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

center_x = int(screen_width/3500 - window_width / 0.97)
center_y = int(screen_height/1 - window_height / 0.62)

root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

def present_time():
    display_time = time.strftime("%I:%M:%S")
    digi_clock.config(text=display_time)
    digi_clock.after(200,present_time)

digi_clock = Label(root, font=("Arial",50),bg="black",fg="red")
digi_clock.pack()

present_time()

root.mainloop()

A: you can try image path and background image concept. First you have to choose image, then it's size and it's position.
IMAGE_PATH = 'PicNameHere.png'
WIDTH, HEIGTH = 200, 50
bkrgframe = BkgrFrame(root, IMAGE_PATH, WIDTH, HEIGTH)
bkrgframe.pack()
Code sample is below.
from tkinter import Tk
from tkinter import Label
import time
from PIL import Image, ImageTk

IMAGE_PATH = 'PicNameHere.png'
WIDTH, HEIGTH = 200, 50

root = Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
root.attributes('-alpha', 1)
root.iconbitmap('klocka.ico (1).ico')
root.geometry('600x400+50+50')

window_width = 255
window_height = 50

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

center_x = int(screen_width/3500 - window_width / 0.97)
center_y = int(screen_height/1 - window_height / 0.62)

root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

bkrgframe = BkgrFrame(root, IMAGE_PATH, WIDTH, HEIGTH)
bkrgframe.pack()

def present_time():
    display_time = time.strftime("%I:%M:%S")
    digi_clock.config(text=display_time)
    digi_clock.after(200,present_time)

digi_clock = Label(root, font=("Arial",50),bg="black",fg="red")
digi_clock.pack()

present_time()

root.mainloop()

A: You can show both an image and text in a Label widget using text, image and compound options:
img_tk = ImageTk.PhotoImage(file="path/to/image.png")
digi_clock = Label(root, font=("Arial",50), fg="red", image=img_tk, compound="center")
digi_clock.pack()

A: from tkinter import Tk
from tkinter import Label
import time
from PIL import Image, ImageTk

root = Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
root.attributes('-alpha', 1)
root.iconbitmap('klocka.ico (1).ico')
root.geometry('600x400+50+50')

bg = PhotoImage(file = "Your_img.png")
canvas1 = Canvas( root, width = 400,
                 height = 400)

canvas1.pack(fill = "both", expand = True)
canvas1.create_image( 0, 0, image = bg,
                     anchor = "nw")
window_width = 255
window_height = 50

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

center_x = int(screen_width/3500 - window_width / 0.97)
center_y = int(screen_height/1 - window_height / 0.62)

root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

def present_time():
    display_time = time.strftime("%I:%M:%S")
    digi_clock.config(text=display_time)
    digi_clock.after(200,present_time)

digi_clock = Label(root, font=("Arial",50),bg="black",fg="red")
digi_clock.pack()

present_time()

root.mainloop()


text:
Q: How to center glossary title without messing up chapter/sections? My problem is that the glossary title should be normal size, bold, all caps and centered.
While Chapter, section and subsection must be all left aligned. So I cannot change section style to suit glossary because it will break the sections original style. Yes, university is specific about such thing (the ruler is my personal touch)...
I do have other glossaries, and they must all not show at ToC.
If I try to use \printacronyms[style=long,title=\centering \uppercase\bfseries {Glossary Title}] as suggested Benjamin comment on this answer, it gives me an error:
Missing { inserted. ...ysection[\glossarytoctitle]{\glossarytitle}
Missing } inserted. ...ysection[\glossarytoctitle]{\glossarytitle}
TeX capacity exceeded, sorry [input stack size=5000]. ...ysection[\glossarytoctitle]{\glossarytitle}

If I try \centering \printacronyms... then chapter and section gets centered but justified with horrible spacing MS-Word-loking because of the few words, but glossary doesn't change. Like this:

This is my MWE:
\documentclass[a5paper]{memoir}
\usepackage[margin=1in]{geometry}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[brazil]{babel}
\selectlanguage{brazil}

\usepackage{titlesec}
\titleformat{\chapter}
  {\fontfamily{phv}\selectfont\bfseries\LARGE}
  {\thechapter}{20pt}{}[\vspace{2ex}\rule{\columnwidth}{0.35cm}]
\titleformat{\section}
  {\fontfamily{fvs}\selectfont\bfseries}
  {\MakeUppercase{\thesection}}{15pt}{}

\usepackage[xindy={language=portuguese},acronym,sort=standard,nomain,nonumberlist=true,nogroupskip]{glossaries}

\setglossarysection{subsection}
\newacronym{pnnl}{PNNL}{Pacific Northwest National Laboratory}

\def\xindylangopt{-L lang/brazil/utf8-lang}
\makeglossaries

\begin{document}

\printacronyms[style=long,title={Glossary Title}]% \centering \uppercase\bfseries {Glossary Title}]
\chapter{Chapter Title}

Text text \gls{pnnl} text text Text text text text Text text text text Text text text text
\section{Section title}
Text text text text Text text text text Text text text text Text text text text
\end{document}

A: The section header for each glossary is set using \glossarysection[\glossarytoctitle]{\glossarytitle} so you just need to redefine that command before you print the glossary. For example:
\documentclass[a5paper]{memoir}
\usepackage[margin=1in]{geometry}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[brazil]{babel}
\selectlanguage{brazil}

\usepackage{titlesec}
\titleformat{\chapter}
  {\fontfamily{phv}\selectfont\bfseries\LARGE}
  {\thechapter}{20pt}{}[\vspace{2ex}\rule{\columnwidth}{0.35cm}]
\titleformat{\section}
  {\fontfamily{fvs}\selectfont\bfseries}
  {\MakeUppercase{\thesection}}{15pt}{}

\usepackage[xindy={language=portuguese},acronym,sort=standard,nomain,nonumberlist=true,nogroupskip]{glossaries}

\setglossarysection{subsection}
\newacronym{pnnl}{PNNL}{Pacific Northwest National Laboratory}

\def\xindylangopt{-L lang/brazil/utf8-lang}
\makeglossaries

\renewcommand{\glossarysection}[2][]{{\centering\bfseries\MakeTextUppercase{#2}\par}}

\begin{document}

\printacronyms[style=long,title={Glossary Title}]

\chapter{Chapter Title}

Text text \gls{pnnl} text text Text text text text Text text text
text Text text text text
\section{Section title}
Text text text text Text text text text Text text text text Text
text text text
\end{document}

This ignores the first argument so it doesn't get added to the table of contents, but the change to \glossarysection means it's no longer a sectioning command, so the definition may need adjusting.


text:
Q: What's a good way of making headers/footers for Bootstrap list-group-items? I'd like to be able to add my own custom headers, footers, etc to list-group-items.  I'm sure there's an easy way to do this but my css skills are sub-par.  Can anyone show me a good way to fix my attempt?
https://jsfiddle.net/r6xt1rnz/36/
I'd like to be able to insert content into the following sections and have them each take up 33% of a list-group-item.

      This is the header

      This is the content

      This is the footer

Thanks!

A: If you want to have vertical height in percentage, you need to use the following code:
body, html {
  margin: 0;
  padding: 0;
  height: 100%;
}

This way, you can control the height in percentages. This method is very much discouraged and will not work with frameworks like bootstrap. But you may give a try with adding a wrapper:

body, html {
  margin: 0;
  padding: 0;
  height: 100%;
}

.first-top {
  height: 30%;
  background: #ccf;
}
.middle-top {
  height: 40%;
  background: #cfc;
}


text:
Q: How can I express these concepts using a single word? I need help with few English words. I'm writing the article about online services and I am stuck. How to say using one word:
a) a person who posts a job (like a person who writes an advert on Freelancer.com) for example: I need a graphic designer or a babysitter etc
b) a person who offers the services for example: I am a cheap plumber and I can do ... but also I can cook for you delicious dinner etc (I believe it's not a tradesman)
c) noun- an order for someone to do something and get paid ( commission or errand?).

A: I am not clear if you want one word for each of a), b) and c) or a single word for the lot. If the second, you're in trouble right away, because a) and b) are people and c) is an abstraction.
Someone who hires free labour on a contract basis could be a "principal" or "client". If someone is a principal, the other one is his "agent". You won't see this among low-level tradesmen though.
The second could be "service provider", but be warned that this is also a respectful punter's term for his prostitute.
"Commission" certainly, especially in the graphic design field, but I would expect a babysitter to refer to just "a job".
"Errand", most certainly not, it has a different meaning.

A: If you don't want to use market terms as client or supplier, what about :

*

*Job offerer

*Job fulfiller

*Job agreement

A: The places where all these types of requests and offers are collected is generally called classified ads. So any one of a, b, or c would be a classified ad. An online service like craigsList is a collection of classified ads. The term comes from the fact that they're organized into many different categories, so each of a, b, and c would likely be in different sections of the site.


text:
Q: reading data from driving license using Tesseract OCR in iPhone I am trying to read information from a driving license of USA. But I am not able to get correct text from the image.
I am trying to read image like above but I am getting some strange result. I am getting something like following:
7 WISCONSIN **i_.* 4' L. _-
DRIVER LICENSE Regular
' Q555-5555-2555-00 35533
I5 .4 ClassDMXxX Enduslmmls TPXMXX J
Sex r mnBLQ EyesBl-U 0000.501" 0.00.100
X Restrictions 0n Back MM 08484005
 X E0". 00-20-2010
It JANE QUINCY
' * 1' 3913' ECIJ-SWILEKgSJVEEQIJNSRIEMREKBVAY
jilfccgbwm suns 20s
BLACK RIVER FALLS w: 54015-0000
Very few of the words are correct. What should I need do to get a more accurate information?
My Code:
Tesseract* tesseract4 = [[Tesseract alloc] initWithDataPath:@"tessdata" language:@"eng"];
[tesseract4 setVariableValue:@"*'\"-_:.0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" forKey:@"tessedit_char_whitelist"];
[tesseract4 setImage:[UIImage imageNamed:@"dlWI.jpg"]];
[tesseract4 recognize];

NSLog(@"%@", [tesseract4 recognizedText]);

A: Try having a look at this question here it explains how to convert the image to grayscale and process the image a bit in order to improve the quality of the results from Tessseract
iOS Tesseract OCR Image Preperation
Also it is worth ensuring that your white list only includes characters that you want to process. So if you don't need : or _ or * then don't include them in the white list and this should clean up the results a bit


text:
Q: How to find the limit points of the set $\{\ a+\alpha\ b \mid a,b \in \mathbb Z, \ \alpha\ \text{is a fixed irrational number} \}$ How to find the limit points of the set $\{\ a+\alpha\ b \mid a,b \in \mathbb Z, \ \alpha\ \text{is a fixed irrational number} \}$
limit point: A point $x$ is said to be a limit point of a non empty set $X,$ if every deleted neighborhood of $x$ contains at least a point in $X.$
Equivalently, There is a sequence $(x_n)$ in $X$ such that $(x_n)\to x.$
Using this definition, how can I find the limit points of the set  $\{\ a+\alpha\ b \mid a,b \in \mathbb Z, \ \alpha\ \text{is a fixed irrational number} \}$ ?
Hints will be greatly appreciated...

A: Let: $$S=\{m\alpha+n;\,m\in \mathbb N, n\in \mathbb Z\}$$ We claim that $\overline S =\mathbb R$. Then, $$S\subset K=\{a+b\alpha;a,b \in \mathbb Z\}$$ imply that $\mathbb R=\overline S\subseteq \overline K\subseteq \mathbb R$.
It's easy to see that, if $\zeta \in S$, then $k\zeta +m \in S$ for any $k\in \mathbb N$ and $m\in \mathbb Z$.
lemma: For every $m\in \mathbb N$, there is $\zeta \in S$ such that $|\zeta|\lt \frac 1m$.
Proof: Consider: $\zeta_n=n\alpha-[n\alpha]$ for $n=1,2,...,m+1$. ([x] denotes the greatest
integer not greater than x.) Then, $\zeta_n\in S$ and $0\lt \zeta_n \lt 1$ and more, if $k\neq j$, $0\neq \zeta_k-\zeta_j \in S$. Consider the $m$ intervals: $(\frac{j-1}{m},\frac{j}{m})$ for $j=1,2,...,m$. Each $\zeta_n$ is irrational and $0\lt \zeta_n \lt 1$. So, each $\zeta_n$, belong to one of this intervals. But, the number of $\zeta_n$ is $m+1$ and the number of this intervals, is $m$. Thus, there are $k\lt i$ such that $\zeta_k,\zeta_i \in (\frac{j-1}{m},\frac{j}{m})$ for some $1\le j\le m$. This means, $|\zeta_k-\zeta_i|\lt \frac 1m$ and $\zeta=\zeta_i-\zeta_k \in S$.
Now, let $x\in \mathbb R$ be arbitrary and $\epsilon \gt 0$ be given. We know that there is $m\in \mathbb N$, such that: $\frac 1m \lt \epsilon$.  Now, by above lemma, there is $\zeta \in S$, such that: $|\zeta|\lt \frac 1m$. If $0\lt \zeta \lt \frac 1m$, we can find $n\in \mathbb Z$, such that, $x+n\gt 0$. then let $k\in \mathbb Z$ be the smallest positive integer such that: $k\zeta \gt x+n$. Then, $\eta=k\zeta-n\in S$ and: $x\lt \eta \lt x+\frac 1m$. If: $-\frac 1m \lt \zeta \lt 0$, we can chose $n\in \mathbb Z$, such that: $x+n \lt0$. Now, chose $k$ the largest positive integer such that: $k\zeta \lt x+n$ and put: $\eta=k\zeta -n \in S$. Then: $x-\frac 1m \lt \eta \lt x$.

A: I'm going to show that the set $A=\{n+m\alpha\,|\,m,n\in\mathbb Z\}$ is dense in $\mathbb R$. For this I will show that $A$ intersects every open interval in the real line.
Suppose that $(a,b)$ is an arbitrary non-empty interval in the real line. Then by Dirichlet's approximation theorem there exists integers $m,n$ such that
$$
0<|m\alpha+n|<b-a
$$
Now for some natural integer $N$ we must have $a<N|m\alpha+n|<b$, but $N|m\alpha+n|\in A$ as we wanted.


text:
Q: Deriving energy eigenstates of free Weyl field I'm wondering if it's possible to derive energy eigenstates for a fermion field without guessing the anti-commutation relations from the start.  I'm taking the Hamiltonian for a Weyl field $\psi$ to be
$$ H=\sum_k \sum_s H_{k,s}, \qquad \sum_s H_{k,s} = \psi_k^\dagger (\vec k \cdot \vec\sigma) \psi_k $$
For $\vec k$ and spin aligned with the $z$ axis, this becomes
$$ H_{k,+} = k (\psi_{k,1r}^2 + \psi_{k,1i}^2) $$
The conjugate momentum to $\psi_k$ is
$ \pi_k = i \psi_k^\dagger$, so the conjugate momenta for the components of $\psi_{k,1}$ would be
$$ \pi_{k,1r} + i \pi_{k,1i} = \psi_{k,1i} + i \psi_{k,1r} $$
I assume we need to pick either the real or imaginary component to take as our canonical coordinate, with the other becoming its conjugate momentum.  Let's take $\psi_{k,1r}$.
$$ \hat H_{k,+} = 2 k \left( \frac12 \hat \pi_{1r}^2 + \frac12 \hat \psi_{1r}^2 \right) $$
The expression in parentheses looks like the Hamiltonian for a harmonic oscillator, which maybe is okay if there's some criterion that excludes all excited states above the first (leaving two states---occupied and unoccupied).
Is the derivation right so far?  Or did we need to know ahead of time that $\psi_{k,1r}$ and $\psi_{k,1i}$ aren't like ordinary real numbers---or that $\hat\pi_{k,1r} \not\equiv -i \, \partial/\partial\psi_{k,1r}$?
EDIT: continuing the thread
Now I'm thinking that rather than picking one of $\{\psi_{k,1r},\psi_{k,1i}\}$ as the canonical coordinate, we should recognize that there's an ambiguity and leave it intact.  For any $0 \leq \alpha \leq 1$, the Hamiltonian can be decomposed as:
$$ \hat H_{k,+} = k \left[ \alpha \left( - \frac{\partial^2}{\partial \psi_{k,1r}^2} + \hat\psi_{k,1r}^2 \right) + (1-\alpha) \left( - \frac{\partial^2}{\partial \psi_{k,1i}^2} + \hat\psi_{k,1i}^2 \right) \right] $$
The eigenstates are then
$$ \Psi_n(\psi_{k,1r},\psi_{k,1i}) = \exp(-\tfrac12 (\psi_{k,1r}^2 + \psi_{k,1i}^2)) H_n(\psi_{k,1r}) H_n(\psi_{k,1i}) $$
where $H_n$ are Hermite polynomials---they are products of harmonic oscillator eigenstates with the same energy level.
The states also need to respect the global phase symmetry $\psi \to e^{i\phi} \psi$
$$ \psi_{k,1r} \to \psi_{k,1r} \cos\phi - \psi_{k,1i} \sin\phi \qquad \psi_{k,1r} \to \psi_{k,1i} \cos\phi + \psi_{k,1r} \sin\phi $$
This means that after the transformation, the wave function needs to still be an eigenstate of the Hamiltonian (for any choice of $\alpha$.  The ground state $\Psi_0$ does respect the symmetry, since $H_0(x) = 1$ and $(\psi_{k,1r}^2 + \psi_{k,1i}^2)$ is invariant.
The first excited state $\Psi_1$ contains an overall factor $\psi_{k,1r} \psi_{k,1i}$, so if we later make a gauge choice $\psi_{k,1i} \equiv 0$, that state would be zero everywhere.

A: The key is to use the phases of the spinor components as the canonical coordinates, as that provides a clean division into coordinates and momenta (versus above where both the real and imaginary parts are integrated over in the action).  The Lagrangian for a Fourier mode is
$$ \mathcal L(k) = i \psi_k^\dagger \sigma^\mu k_\mu \psi_k $$
Let's decompose the spinor as magnitude-phase:
$$ \psi_k = \begin{pmatrix} R_1 e^{-i\phi_1} \\ R_2 e^{-i\phi_2} \end{pmatrix} $$
In the action we will have an integral over $i\psi^\dagger \dot\psi \,\mathrm dt = i \psi^\dagger \mathrm d \psi$.  Keeping the real part, for the top component we have
$$ \mathrm{Re}[i (R_1 e^{i\phi_1})(\mathrm d R_1 \, e^{-i\phi_1} - i R_1 \mathrm d\phi_1 e^{-i\phi_1})] = R_1^2 \, \mathrm d \phi_1 $$
So the action looks like
$$ S = \int R_1^2 \, \mathrm d \phi_1 + \int R_2^2 \, \mathrm d \phi_2 - \int H \, \mathrm d t $$
For a $k$ whose spatial part is oriented along the $+z$ axis, the Hamiltonian is
$$ H_k = k (R_1^2 - R_2^2) $$
The magnitude-squared of each spinor component is the conjugate momentum to the phase angle $\phi_1$ or $\phi_2$.
$$ \hat{(R_1^2)} = -i\hbar \frac{\partial}{\partial\phi_1} \qquad \hat{(R_1)^2} = -i \hbar \frac{\partial}{\partial\phi_2} $$
$$ \hat H = -i\hbar k \left( \frac{\partial}{\partial\phi_1} - \frac{\partial}{\partial\phi_2} \right) $$
We require that $\Psi(2\pi) = \Psi(0)$, which limits valid eigenfunctions of $\hat H_k$ to
$$ \Psi_{m,n}(\phi_1,\phi_2) = \exp \left( \frac{i}{\hbar} (m \phi_1 + n \phi_2) \right) $$
for $m,n \in \mathbb Z$.  The magnitude-squared cannot be negative.  Its eigenvalues are
$$ r_1^2 = m \qquad r_2^2 = n $$
so we are constrained to those solutions with $m \geq 0, \, n \geq 0$, with energy eigenvalues
$$ E_{m,n} = \hbar k(m-n) $$
At this point, it seems that we can have any number of particles with positive or negative energy contributions of $\hbar k$.  If $m$ and $n$ are unbounded, then the Hamiltonian is not bounded from below.  Only integer values are allowed for the $R^2$'s, meaning that (if we take the magnitude to be nonnegative)
$$ R_1,R_2 \in \{0,1,\sqrt{2},\sqrt{3},\cdots\} $$
For the $0,1$ values, we have that $R = R^2$, which actually lets us translate the $\hat H_k$ to a second order Hamiltonian.  Hamiltonians like to be quadratic in the momenta.
$$ \hat H = \hbar k \left( -\frac{\partial^2}{\partial\phi_1^2} + \frac{\partial^2}{\partial\phi_2^2} \right) $$
For these special values, it is also possible to represent other parameterizations of the spinor with finitely many terms.  For example, the real part of the first component of $\psi$:
$$ \psi_{1,R} = \cos(\phi) \, \sqrt{R^2} $$
The square root function does not have a Taylor series at $0$ (already a red flag?), so let's take it at $1$.
$$ \psi_{1,R} = \cos(\phi) \left[ 1 + \frac{R^2-1}{2} - \frac{(R^2-1)^2}{8} + \cdots \right] $$
$$ \hat\psi_{1,R} = \cos(\phi) \left[ 1 + \frac{1}{2}\left( -i\hbar\frac{\partial}{\partial\phi_1} - 1 \right) - \frac{1}{8}\left( -\hbar^2 \frac{\partial^2}{\partial\phi_1^2} + 2 i\hbar \frac{\partial}{\partial\phi_1} + 1 \right) + \cdots \right] $$
If we allow $\lvert{m}\rvert,\lvert{n}\rvert > 1$, then we need to take infinitely many derivatives just to pull out the components of the spinor.  For $R_1^2 \in \{0,1\}$, this is simply
$$ \hat\psi_{1,R} = -i\hbar\cos(\phi)\, \frac{\partial}{\partial\phi_1} $$
I don't know if this is sufficient reason to exclude all $m,n > 1$, but I find it convincing enough.  With just two states $m = 0$ and $m=1$ for each wave number and spin orientation, the creation/annihilation operators can be expressed as $2\times2$ matrices
$$ \hat b^\dagger = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix} \qquad \hat b = \begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix} $$
which exhibit the anti-commutation relations
$$ bb^\dagger + b^\dagger b = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \quad bb = b^\dagger b^\dagger = \begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix} $$


text:
Q: Remove the Shadow in Bootstrap 2 When I have data inside of the input, the shadow will display in the input's background and I want to remove it in bootstrap 2.
I just want a white background in the input box only.
Please remember that I'm using bootstrap 2!
Thanks!
http://jsbin.com/vuzikonazu/edit?html,css,js,output

A: Add box-shadow:none; in input class as below
.text-input-wrapper input {
  border:none;
  background:none;
  outline:none;
  padding:0 0;
  margin:0 0;
  font:inherit;
  box-shadow:none;

}


text:
Q: How to binding an array of string using translate pipe from ngx-translate I have this child component which has an input that receive an array of string:
<child-component list="['yes','no']"> </child-component>

I'm trying to send the data with the pipe translate from ngx-translate.
<child-component list="[{{'yes' | translate}},{{'no' | translate}}]"> </child-component>

but I didn't work.
I don't want to use the pipe in the child component code, so, is there a way to send it already translated?

A: Just translate your labels directly in the component, like:
export class AppComponent implements OnInit {
    labels: string[] = ['yes', 'no'];

    constructor(private translateService: TranslateService) {}

    ngOnInit(): void {
        this.translateService
            .get(this.labels)
            .subscribe((res: string[]) => {
                console.log(res);
                //=> translated labels
            });

        // Or
        this.translateService.instant('yes');
        this.translateService.instant('no');
    }
}


text:
Q: Value Bindings in SML? Could someone please help. I don't get the sequence of evaluation here and how we got values of "ans". e.g. in the first example there's no value of y and I'm not sure whether this returns a pair or calls x ! (fn y => y x). It would be very helpful if you can Trace each expression.
val x = 1
val f = (fn y => y x)
val x = 7
val g = (fn y => x - y)
val ans = f g

val ans = 6 : int

=====================================
fun f p =
let
val x = 3
val y = 4
val (z,w) = p
in
(z (w y)) + x
end
val x = 1
val y = 2
val ans = f((fn z => x + z), (fn x => x + x + 0))

val ans = 12 : int

A: There are a few things which help make problems like this much clearer
when trying understand an alien function Lexical scoping works.

*

*add in types to the parameters and return values without modifying the program, the compiler will tell you if you get it wrong...

*replace anonymous functions with named ones.

*rename variable bindings that have the same names but refer to different lexical scope.

*remove variable bindings that only get used once.

binding a value to a name does not actually perform any computation,
so is merely for the benefit of the reader, if it is not doing that job
it merely serves to obfuscate, then by all means remove it.
fun f (y1 : int -> 'a) = y1 1 : 'a;
fun g (y2 : int) = 7 - y2 : int;
val ans : int = f g;

so g is given as a parameter to f, f calls g giving it the parameter x having the value 1 making y2 = 1, which g subtracts 7 - 1 returning 6.
the return value of g is an int, thus f's 'a type when g is applied to it is an int.
for the 2nd one clean it up a bit, I pulled the anonymous fn's out into their own and named values and call f (foo, bar) to make it more readable...
fun f p =
 let val x = 3
     val y = 4
     val (z, w) = p
  in (z (w y)) + x end
fun foo z = z + 1;
fun bar x = x * 2;
val ans = f(foo, bar);

Finally, we can get rid of the let values which are only used once
and replace the (z,w) = p with just (z, w) as a parameter to the function which should be much easier to follow
fun f (z, w) = (z (w 4)) + 3
fun foo z = z + 1;
fun bar x = x * 2;
val ans = f(foo, bar);
val ans = ((4 * 2) + 1) + 3


text:
Q: Iterate arraylist and send email by grouping values I have an ArrayList like below
ArrayList<String> fList = new ArrayList<>();
    fList.add("100510-0001");
    fList.add("100510-0001");
    fList.add("100513-0004");
    fList.add("100510-0002");
    fList.add("100510-0001");
    fList.add("100513-0005");
    fList.add("100513-0006");
    fList.add("100518-0006");
    fList.add("100599-0001");
    fList.add("100593-0009");

I need to send an email based on first 6 characters of the List values.
Example:
 I have 100510 repeated 4 times in the list so I need to send all 4 records in the same email, like below hardcode one.
I have 100513 3 times, I can have n number of lists but I need to do recursion/iteration and send the email with the same records i.e 100510 in a separate email and 100513 in a separate email etc...
Any help?
ArrayList<String> subList = new ArrayList<>();
    for (int i = 0; i < fList.size(); i++) {
       String subString =  fList.get(0).split("-")[0];
        if(fList.get(i) == "100510"){
            subList.add(fList.get(i));
            createEmail(subList);
        }
        if(fList.get(i) == "100513"){
            subList.add(fList.get(i));
            createEmail(subList);
        }
    }

A: If all you need is to send one e-mail per "prefix", then all you need to do is group:
Map<String, List<String>> distinctMap = fList.stream()
            .collect(Collectors.groupingBy(s -> s.split("-")[0]));

distinctMap.forEach((str1, list) -> {
    System.out.println("Sending e-mail for prefix " + str1);
    createEmail(list);
});

Of course you can do that using your for-loop, but you should only send the e-mail after all iterations:
Map<String, List<String>> emailsByPrefix = new HashMap<>();

for (int i = 0; i < fList.size(); i++) {

    String subString = fList.get(i).split("-")[0];

    emailsByPrefix.merge(subString, Arrays.asList(fList.get(i)), (list1, list2) -> {
        List<String> merged = new ArrayList<>();
        merged.addAll(list1);
        merged.addAll(list2);

        return merged;
    });
}

for (Entry<String, List<String>> emailEntry : emailsByPrefix.entrySet()) {
    System.out.println("Sending e-mail for prefix " + emailEntry.getKey());
    createEmail(emailEntry.getValue());
}

A: You can sort the original list, collect subList until first part changes, then send the subList each time the first part changes.
Collections.sort(fList);
String lastPart1 = null;
List<String> subList = null;
for (int i = 0; i < fList.size(); i++) {
   String strPart1 =  fList.get( i ).split("-")[0];
   String strPart2 =  fList.get( i ).split("-")[1];
    if( !strPart1.equals(lastPart1) ){
         if(subList!=null){ //Send the last collected subList
             createEmail( lastPart1, subList );
         }
         subList = new ArrayList<>();
         subList.add (strPart2);
         lastPart1 = strPart1;

    }else{
         subList.add (strPart2);
    }
}


text:
Q: More Efficient If\Else? Is there possibly a more condensed/efficient way of writing out this if/else statement? I am having to do a check for null on every single field in this database (close to 200 fields) and the code is going to look quite messy by the end. :\
if (dr["OLD_NUMBER"] != DBNull.Value)
{
    lblOldNumber.Text = dr["OLD_NUMBER"].ToString();
}
else
{
    lblOldNumber.Text = string.Empty;
}
// A bunch more with different lbls and columns

A: You could do
lblOldNumber.Text = dr["OLD_NUMBER"] != DBNull.Value ? dr["OLD_NUMBER"].ToString() : string.Empty;

The above statement would require less lines and looks more readable to me.

A: You can get rid of the if entirely.
DBNull.Value.ToString() returns an empty string.

A: lblOldNumber.Text = string.Empty;
if (dr["OLD_NUMBER"] != DBNull.Value)
{
    lblOldNumber.Text = dr["OLD_NUMBER"].ToString();
}

or you cam make function like
void ApplyValue(Label label,object value, string defaultValue){
     label.Text =defaultValue;
     if (value != DBNull.Value)
     {
         label.Text = value.ToString();
     }
}

and use next code
ApllyValue(lblOldNumber,dr["OLD_NUMBER"],string.Empty);

A: you could use the following:
lblOldNumber.Text = dr["OLD_NUMBER"] != DBNull.Value ? dr["OLD_NUMBER"].ToString() : string.Empty;

More information about the ?: operator instead of if, can be found here: (C# Reference)

A: As a rule of thumb when you see this sort of repetition, write a function to do your processing.
string FormatIt(object value)
{
   return value.ToString(); // or whatever the logic is like
}

Then:
lblOldNumber.Text = FormatIt(dr["OLD_NUMBER"]);

So, if you had to modify your code to format money or smth like that, you have one place to change.

A: Something like this:
var labels = new Dictionary<string, YourLabelClass>
                         {
                             {"OLD_NUMBER", lblOldNumber},
                             //Add your 200 fields here
                             {"ANOTHER_NUMBER", lblAnotherNumber},
                         };

        foreach (var label in labels)
        {
            label.Value.Text = dr[label.Key].ToString();
        }

A: You could remove the null values from your data set when you query the database.
var result = (context.MyTable.Where(c => c.OLD_NUMBER != null));

A: I'd probably write a method:
void TextOrNull(object item, Label lbl)
{
  lbl.Text = item != DBNull.Value ? item.ToString() : String.Empty;
}

And call it like:
TextOrNull(dr["OLD_NUMBER"], lblOldNumber);

A: I would make a method that has this in, something like:
private void setLabelText( IDataRecord dr, string columnName, Label label )
{
    label.Text = string.Empty
    if (dr[columnName] != DBNull.Value)
    {
        label.Text = dr[columnName].ToString();
    }
}

Then simply call it with the appropriate labels and record names, etc.
setText( dr, "OLD_NUMBER", lblOldNumber );

A: I haven't experimented with this much but there is an ItemArray on the DataRow class that will return an object array of the items in the DataRow.  Might be able to set up a loop and test values that way rather than hardcoding the name of the key.
Again not sure if this will work as I don't have a test scenario set up on my PC, but like this?
foreach (var col in dataRow.ItemArray)
{
    if(DBNull.Value != col)
        lbl.Text = col.ToString()
}


text:
Q: Автоматический запуск всех приложений в полноэкранном режиме linux как сделать так, чтобы любая программа всегда открывалась в полном окне? Стандартный оконный менеджер linux mint. Если такое невозможно, то как сделать то же для конкретного приложения(например, терминала)?

A: Когда-то в стародавние времена, когда тайловые менеджеры ещё не были популярны, я использовал программу devilspie для этого.
(if
(is (application_name) "Терминал")
(start
(maximise)
)
)

без условия - для всех окон.
посмотри gdevilspie, devilspie, devilspie2, может winctl


text:
Q: Fastest way of replacing strings with its counterpart I need to replace acronym slangs within a string to its expanded part. The dataset for the slang I use is this one with over 3k items. This is my current code for the process:
import pandas as pd

slangs = pd.read_csv('slang.csv', index_col=[0])

def expand_slang_acronyms():
    word_list = 'foo brb bar'.split(' ')
    for i in range(len(word_list)):
        for j in range(len(slangs)):
            if word_list[i] == slangs.loc[j, 'acronym']:
                word_list[i] = slangs.loc[j, 'expansion']

    print(' '.join(word_list)) # 'foo be right back bar'

Running it as is is quite fast but I need to replace thousands of strings. Timing the code executing just 100 times:
from timeit import timeit
timeit(expand_slang_acronyms, number=100)

In this instance it output 6.519681000005221 which is really slow considering it's only 100 times. I need a faster way to do this.

A: I think there are many ways to do this. Here is one way to speed up the process.
import pandas as pd

slangs = pd.read_csv('slang.csv')
slang_dict = dict(zip(slangs['acronym'], slangs['expansion']))

def expand_slang_acronyms():
    word_list = 'foo brb bar'.split(' ')
    for i in range(len(word_list)):
        if word_list[i] in slang_dict:
            word_list[i] = slang_dict[word_list[i]]

    print(' '.join(word_list)) # 'foo be right back bar'

timeit(expand_slang_acronyms, number=100)

This should result in a performance boost, as dictionary lookups are O(1) on average, compared to O(n) for iterating through a DF.


text:
Q: How to check if string is valid URL to image? I have the following class:
require 'uri'

class Images

  IMAGE_NOT_FOUND = '/images/no_image.gif'

  attr_accessor :url

  def initialize(parameters = {})
    @url = parameters.fetch(:url, IMAGE_NOT_FOUND)
    @url = IMAGE_NOT_FOUND unless @url =~/^#{URI::regexp}$/
  end

end

holding URL to image. I have checked some questions and add URL validation, but I need to improve it validating URLs pointing to images only.If validation fails, I want to use default image showing there is some issue.
Note, the current validation of the URL is not working with relative paths. For example, the following url is valid as image source /images/image1.png but the current validation is not recognizing it.
Could anyone tell if this is possible using URI?

A: Assuming that you want to only validate the URLs pointing to image type of files.
For eg: http://www.xyz.com/logo.png or http://www.xyz.com/logo.gif or http://www.xyz.com/logo.jpg
Here's the solution:
require 'uri'

class Images

  IMAGE_NOT_FOUND = '/images/no_image.gif'

  attr_accessor :url

  def initialize(parameters = {})
    @url = parameters.fetch(:url, IMAGE_NOT_FOUND)
    @url = IMAGE_NOT_FOUND unless ((File.extname(@url) =~/^(.png|.gif|.jpg)$/ )||(@url =~ /^#{URI::regexp}$/))
  end

end

The above example will only allow url's pointing to images with extension .png or .gif or .jpg and rest would be set to IMAGE_NOT_FOUND. Add more extensions if you want to.


text:
Q: jquery returning to original state on mouseout We are changing a number of things in our html on hover:
$('.zentriert')
.hover(function(){
    if(!$(this).is(".open")) {
    $(this).animate({opacity: 1}, 150);
    $(this).find('img').css({'position': 'relative'}).animate({top: -10}, 150);
    $(this).find('.beschreibung').css({'display': 'block'}).animate({opacity: 1, top: -10}, 150);
    $(this).addClass('open')
    }})

What's the best way to return everything to its original state on mouseout? This ISN'T working:
$('.zentriert')
.mouseout(function(){
    if($(this).is(".open")) {
    $(this).animate({opacity: 0.17}, 150);
    $(this).find('img').animate({top: 10}, 150);
    $(this).find('.beschreibung').animate({opacity: 0, top: 10}, 150).css({'display': 'none'});
    $(this).removeClass('open')
    }})

Thanks in advance for any help!

A: The hover event in jQuery takes 2 callback functions. The first one is triggered when user hover the item and the second for when it leaves
Try
$(".zentriert").hover(
   function() {
     if(!$(this).is(".open")) {
    $(this).animate({opacity: 1}, 150);
    $(this).find('img').css({'position': 'relative'}).animate({top: -10}, 150);
    $(this).find('.beschreibung').css({'display': 'block'}).animate({opacity: 1, top: -10}, 150);
    $(this).addClass('open')
    }
   },
   function() {
     if($(this).is(".open")) {
    $(this).animate({opacity: 0.17}, 150);
    $(this).find('img').animate({top: 10}, 150);
    $(this).find('.beschreibung').animate({opacity: 0, top: 10}, 150).css({'display': 'none'});
    $(this).removeClass('open')
    }
   }
);


text:
Q: how do I set a column to be the default sort column with Telerik RadGridView in Silverlight I have a RadGridView control in a  silverlight project and would like to have the grid come up sorted by the name column. I tried placing the attribute SortingState="Ascending" on the column definition for the name. I do not see any other attributes that might accomplish this. Does anyone know how to make this happen?

A: You will want to add a SortDescriptor to the grid
<telerik:RadGridView.SortDescriptors>
    <telerik:SortDescriptor Member="Name" SortDirection="Ascending" />
</telerik:RadGridView.SortDescriptors>

A: Also, what about the 'ColumnSortDescriptor'?
http://demos.telerik.com/silverlight/#GridView/Sorting
There are examples and code there.


text:
Q: ZF2 Restful API not routing options method I am testing my zf2 restful api by sending an OPTIONS command to it but its going right into the action defined in the router and not the options() method.
Router:
'router' => array(
    'routes' => array(
        'edatafeed' => array(
            'type'    => 'Zend\Mvc\Router\Http\Literal',
            'options' => array(
                'route'    => '/api',
                'defaults' => array(
                    '__NAMESPACE__'    => 'Application\Controller',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'default' => array(
                    'type'    => 'Segment',
                    'options' => array(
                        'route'    => '/:controller[/:action][/]',
                        'constraints' => array(
                            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        ),
                        'defaults' => array(
                        ),
                    ),
                ),
            ),
        ),
    ),
),

Controller:
class SomeController extends ApiController
{
    protected $dm;

    private function getDm()
    {
        $this->dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
    }

    public function executeAction()
    {
        return new JsonModel(array(
            'ok' => false,
            'data' => null,
        ));
    }
}

ApiController:
class ApiController extends AbstractRestfulController
{

    protected function methodNotAllowed()
    {
        $this->response->setStatusCode(405);
        throw new \Exception('Method Not Allowed');
    }

    public function options()
    {
        $response = $this->getResponse();
        $headers  = $response->getHeaders();

        $headers->addHeaderLine('Allow', implode(',', array(
            'GET',
            'POST',
        )))
        ->addHeaderLine('Content-Type','application/json; charset=utf-8');
        return $response;
    }
}

When I sent an OPTIONS command to /api/some/execute it goes right into the execute action and not into the options method. Is there something I'm missing in the routing? I thought that sending any OPTIONS command would route it to options().
Thanks

A: So it seems that the AbstractRestfulController actually checks to see if the request is to a custom action before checking the request method type. So since I defined an action called "execute" it routes straight to executeAction() before checking if its an OPTIONS command. I had to override the onDispatch() method in my ApiController class and only route to my custom method if its a GET, POST, or UPDATE command. Otherwise route to appropriate method type method.
This is the code I modified:
    // RESTful methods
    $method = strtolower($request->getMethod());

    // Was an "action" requested?
    $action  = $routeMatch->getParam('action', false);
    if ($action &&
        ($method == 'get' || $method == 'post' || $method == 'update')) {
        // Handle arbitrary methods, ending in Action
        $method = static::getMethodFromAction($action);
        if (! method_exists($this, $method)) {
            $method = 'notFoundAction';
        }
        $return = $this->$method();
        $e->setResult($return);
        return $return;
    }

Hope this helps someone else in the future.

A: I've had this problem and solve it as follows:
class ApiRestfullController extends AbstractRestfulController {

    protected $allowedCollectionMethods = array(
        'POST',
        'GET'
    );

    public function setEventManager(EventManagerInterface $events) {
        parent::setEventManager($events);

        $events->attach('dispatch', function ($e) {
            $this->checkOptions($e);
        }, 10);
    }

    public function checkOptions($e) {
        $response = $this->getResponse();
        $request = $e->getRequest();
        $method = $request->getMethod();

        if (!in_array($method, $this->allowedCollectionMethods)) {
            $this->methodNotAllowed();
            return $response;
        }
    }

    public function methodNotAllowed() {
        $this->response->setStatusCode(
            \Zend\Http\PhpEnvironment\Response::STATUS_CODE_405
        );
        throw new Exception('Method Not Allowed');
    }
}

I hope this will help solve the problem.


text:
Q: What are the differences between "T a", "T a()" and "T a=T()" where T is a class? Let T a C++ class.
Is there any difference in behaviour between the following three instructions?
T a;
T a();
T a = T();

Does the fact that T provides an explicit definition for a constructor that takes no parameter change anything with respect to the question?
Follow-up question: what about if T provides a definition for a constructor that takes at least one parameter? Will there then be a difference in behaviour between the following two instructions (in this example I assume that the constructor takes exactly one parameter)?
T a(my_parameter);
T a = T(my_parameter);

A: T a; performs default initialization.
T a = T(); performs value initialization.
T a(); does not declare a variable named a. It actually declares a function named a, which takes no arguments and whose return type is T.
The difference between default initialization and value initialization is discussed here.


text:
Q: Adding direct reference to a WCF project Wondering if somebody done it before. We are using WCF in our current architecture and when internally not going over the boundaries I would like the ability to reference the project directly.
I don't want to use tcp or named pipes, I would like to know if is technically possible to alternate between a project reference or normal communication with WCF eg tcp-http etc..
Is there any example or approaches to achieve this?
Looked on google and stackoverflow but I could not find an answer if the title was the same
Many thanks


text:
Q: Assign button text dynamically via a loop I am trying to assign button controls text dynamically by using a loop like the following:
int ButtonNumber = 1;

while (ButtonNumber < 10)
{
    //WHAT TO DO HERE!?
    ButtonNumber++;
}

I wanna avoid the following:
button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";

A: Ideally, don't have button1, button2 etc as variables in the first place. Have a collection (e.g. a List<Button>):
private List<Button> buttons = new List<Button>();

(EDIT: You'd need to populate this somewhere, of course...)
then to update the text later:
for (int i = 0; i < buttons.Count; i++)
{
    buttons[i].Text = "I'm button " + i;
}

This doesn't play terribly nicely with the designer, unfortunately.
You can fetch a control by ID, but personally I try not to do that. If you really want to:
for (int i = 1; i <= 10; i++)
{
    Control control = Controls["button" + i];
    control.Text = "I'm button " + i;
}

A: Create an array of buttons:
Button[] buttons = new Button[10];
for(int i = 1; i < 10; i++)
{
   buttons[i] = new Button();
   buttons[i].Text = "";
}

A: You can always use this.Controls.Find() to locate a named control in WinForms.

A: You can also do like this simply, assuming if you have all buttons in your form
foreach (Control c in this.Controls)
            {
                if (c is Button)
                {
                    c.Text = "MyButton" + (c.TabIndex + 1);
                }
            }

A: // try this
         Button btn;
         for (int n_i = 0; n_i < 10; n_i++)
            {
            btn = (Button)Controls.Find("button" + n_i,true)[0];
            btn.Text = "";
            }


text:
Q: Can a Microsoft DHCP server be configured update a Microsoft DNS server with a configured hostname, ignoring the client supplied name? I have been struggling with this for a few days now, and am really at my wit's end.  Our infrastructure is very heterogeneous with a mix of hardware devices and virtual machines running a variety of operating systems.  This issue is present in situations where "fixing it on the client" is simply not an option, so please, no answers in that vein.
The TL;DR is that I cannot figure out how to simply enter a DHCP reservation with a MAC, IP, & hostname that is "static" for lack of a better word.  Nothing I do will allow the DHCP server to create the DNS record while also preventing the DHCP client from changing it.
For example, our fiber channel array controllers have dual NICs for redundancy, with auto-generated hostnames that cannot be manually configured.  In our old setup, I simply made DHCP reservations for their MAC addresses with host names such as "array1ctrl1" and "array1ctrl2".  The name & IP were automatically entered into DNS with a matching address when the DHCP reservation was created.
The Microsoft DHCP server works differently.  It does not create a matching DNS record until the DHCP client requests the lease, and when that happens, it updates both the reservation & DNS with the (unwanted) client supplied hostname.
There are similar issues with other bits of hardware and software that all boil down to the same overall issue -- the seeming inability to create a DHCP reservation with a specified hostname and have it remain as entered regardless of how the DHCP client identifies itself.
After a lot of trial and error, and as much google searching as I was able to stomach, it's starting to appear that this is simply impossible to do in a MS DHCP server.  If that's the case, so be it, but I'd like to know for certain if so.
Thanks in advance!


text:
Q: How to perform List of boolean expression together in recursion I have a Dictinary of bool and string which contain an operation and want to get the output in recursion how this can be achieved.
IDictionary<bool , string> lstIfResult = null;

suppose this list contains :
{
  { true,  "AND" },
  { false, "OR"  },
  { true,  "AND" }
}

My code is :
for (int i = 0; i < lstIfResult.Count(); i++)
{
    bool res = getBinaryOprResult(lstIfResult.ElementAt(i) , lstIfResult.ElementAt(i + 1));
}

private static bool getBinaryOprResult(KeyValuePair<bool, string> firstIfResult,
                                       KeyValuePair<bool, string> secondIfResult)
{
    switch (firstIfResult.Value)
    {
        case "AND":
            return firstIfResult.Key && secondIfResult.Key;
        case "OR":
            return firstIfResult.Key || secondIfResult.Key;
        default:
            return false;
    }
}

how can I recurse this function to get Key element 1 equated with 2 and then their result equated with the third.
and operation used between 1 & 2 is 1st and between their output to third is second. last key element operation will be ignored.
Thanks in advance.

A: First, let's extract model (when given a name, e.g. "OR" we return an operation to perform):
private static Dictionary<string, Func<bool, bool, bool>> s_Operations =
  new Dictionary<string, Func<bool, bool, bool>>(StringComparer.OrdinalIgnoreCase) {
    {  "AND", (a, b) => a && b},
    {   "OR", (a, b) => a || b},
    {  "XOR", (a, b) => a ^ b },
    { "TRUE", (a, b) => true  },
    {"FALSE", (a, b) => false },
    //TODO: add more operations, synonyms etc.
  };

Then you can Aggregate with a help of Linq (note, that the last operation - "OR" will be ignored):
using System.Linq;

...

// I've created list, but any collection which implements
// IEnumerable<KeyValuePair<bool, string>> will do
IEnumerable<KeyValuePair<bool, string>> list = new List<KeyValuePair<bool, string>>() {
  new KeyValuePair<bool, string>( true, "AND"),
  new KeyValuePair<bool, string>(false,  "OR"),
  new KeyValuePair<bool, string>( true,  "OR"),
};

...

// ((true && false) || true) == true
bool result = list
 .Aggregate((s, a) => new KeyValuePair<bool, string>(
    s_Operations[s.Value](s.Key, a.Key),
    a.Value))
 .Key;

A: You have an error like "OutOfRange" becauseof lstIfResult.ElementAt(i+1) in for loop.
If you want to ignore last element , try to use
for (int i=0; i<lstIfResult.Count-1; i++) {
bool res = getBinaryOprResult(lstIfResult.ElementAt(i) , lstIfResult.ElementAt(i+1));


text:
Q: Django: row still displayed after being deleted - because of caching? I've written a Django app that uses DataTables. The problem is when I delete a row from the table it's still displayed in the table when running against nginx/gunicorn. However, it works correctly when I'm running against the Django test server. So if I start a server with this command line:
python manage.py runserver 192.168.0.1:8000

everything works fine. That is, I delete the row, the table refreshes, and the deleted row is not displayed.
This is a summary of the HTTP calls:
// An initial GET command to populate the table
GET /myapp/get_list (returns a list to display)

// I now select a row and delete it which causes this POST to fire
POST /myapp/delete (deletes a row from the list)

// After the POST the code automatically follows up with a GET to refresh the table
GET /myapp/get_list (returns a list to display)

The problem is when I use nginx/gunicorn the second GET call returns the same list as the first GET including the row that I know has been deleted from the backend database.
I'm not sure it's a caching problem either because this is the response header I get from the first GET:
Date    Fri, 23 Dec 2011 15:04:16 GMT
Last-Modified   Fri, 23 Dec 2011 15:04:16 GMT
Server  nginx/0.7.65
Vary    Cookie
Content-Type    application/javascript
Cache-Control   max-age=0
Expires Fri, 23 Dec 2011 15:04:16 GMT

A: The problem can be solved also by sending an added parameter to the server so that the browser doesn't cache the call. With jQuery you can simply use:
$.ajaxSetup({ cache: false});

Otherwise you must creat manually the parameter. Usually you create a timestamp
var nocache = new Date().getTime();
//send nocache as a parameter so that the browser thinks it's a new call

A: You can use Django's add_never_cache_headers or never_cache decorator to tell the browser not to cache given request. Documentation is here. I thinks it's cleaner solution than forcing the cache off in the javascript.
    from django.utils.cache import add_never_cache_headers

    def your_view(request):
        (...)
        add_never_cache_headers(response)
        return response

    from django.views.decorators.cache import never_cache

    @never_cache
    def your_other_view(request):
            (...)

A: try this
oTable.fnDeleteRow( anSelected, null, true );

and b.t.w what version of datatables do you use?

A: I fixed the problem by changing

GET /myapp/get_list

to

POST /myapp/get_list

After doing this, I no longer get a cached response.


text:
Q: Webpack-dev-server hot-reload with react-router I use yeoman to set up my project with react and webpack.
Then, I manually added react-router to the project.
The hot-reload works fine until I have paths.
So in my index.js, I have
<Provider store={store}>
<Router history={browserHistory}>
  <Route path="/" component={App}>
    <IndexRoute component={Dashboard}/>
    <Route path="/app" component={Nav}>
      <Route path="/app/payable/export" component={Export}/>
    </Route>
  </Route>
  <Route path="*" component={NotFound}/>
</Router>

The hot-reload works fine for components: App and Dashboard because there path is just "/".
But the hot-reload doesn't work for Export.
I got this error:
http://localhost:9300/app/payable/assets/31f035eb918b53b2078f.hot-update.json 404 (Not Found)

It seems it is appending the route path in the resource path, but webpack only generates hot-reload files under "/assets/".
However, if I use hashHistory in react-router, I don't have problem. Only when I use broswerHistory.
Here's my webpack config:
const path = require('path');
const srcPath = path.join(__dirname, '/../src');
...
{
publicPath: '/assets/',
srcPath: srcPath
}


text:
Q: How to mock aiohttp.client.ClientSession.get async context manager I have some troubles with mocking aiohttp.client.ClientSession.get context manager. I found some articles and here is one example that seems was working: article 1
So my code that I want to test:
async_app.py
import random
from aiohttp.client import ClientSession

async def get_random_photo_url():
    while True:
        async with ClientSession() as session:
            async with session.get('random.photos') as resp:
                json = await resp.json()
        photos = json['photos']
        if not photos:
            continue
        return random.choice(photos)['img_src']

And test:
test_async_app.py
from asynctest import CoroutineMock, MagicMock, patch

from asynctest import TestCase as TestCaseAsync

from async_app import get_random_photo_url

class AsyncContextManagerMock(MagicMock):
    async def __aenter__(self):
        return self.aenter

    async def __aexit__(self, *args):
        pass

class TestAsyncExample(TestCaseAsync):
    @patch('aiohttp.client.ClientSession.get', new_callable=AsyncContextManagerMock)
    async def test_call_api_again_if_photos_not_found(self, mock_get):
        mock_get.return_value.aenter.json = CoroutineMock(side_effect=[{'photos': []},
                                                                       {'photos': [{'img_src': 'a.jpg'}]}])

        image_url = await get_random_photo_url()

        assert mock_get.call_count == 2
        assert mock_get.return_value.aenter.json.call_count == 2
        assert image_url == 'a.jpg'

When I'm running test, I'm getting an error:
(test-0zFWLpVX) ➜  test python -m unittest test_async_app.py -v
test_call_api_again_if_photos_not_found (test_async_app.TestAsyncExample) ... ERROR

======================================================================
ERROR: test_call_api_again_if_photos_not_found (test_async_app.TestAsyncExample)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/kamyanskiy/.local/share/virtualenvs/test-0zFWLpVX/lib/python3.6/site-packages/asynctest/case.py", line 294, in run
    self._run_test_method(testMethod)
  File "/home/kamyanskiy/.local/share/virtualenvs/test-0zFWLpVX/lib/python3.6/site-packages/asynctest/case.py", line 351, in _run_test_method
    self.loop.run_until_complete(result)
  File "/home/kamyanskiy/.local/share/virtualenvs/test-0zFWLpVX/lib/python3.6/site-packages/asynctest/case.py", line 221, in wrapper
    return method(*args, **kwargs)
  File "/usr/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
    return future.result()
  File "/home/kamyanskiy/.local/share/virtualenvs/test-0zFWLpVX/lib/python3.6/site-packages/asynctest/_awaitable.py", line 21, in wrapper
    return await coroutine(*args, **kwargs)
  File "/home/kamyanskiy/.local/share/virtualenvs/test-0zFWLpVX/lib/python3.6/site-packages/asynctest/mock.py", line 588, in __next__
    return self.gen.send(None)
  File "/home/kamyanskiy/work/test/test_async_app.py", line 23, in test_call_api_again_if_photos_not_found
    image_url = await get_random_photo_url()
  File "/home/kamyanskiy/work/test/async_app.py", line 9, in get_random_photo_url
    json = await resp.json()
TypeError: object MagicMock can't be used in 'await' expression

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (errors=1)

So I've tried to debug - here is what I can see:
> /home/kamyanskiy/work/test/async_app.py(10)get_random_photo_url()
      9                 import ipdb; ipdb.set_trace()
---> 10                 json = await resp.json()
     11         photos = json['photos']

ipdb> resp.__aenter__()
<generator object CoroutineMock._mock_call.<locals>.<lambda> at 0x7effad980048>
ipdb> resp.aenter
<MagicMock name='get().__aenter__().aenter' id='139636643357584'>
ipdb> resp.__aenter__().json()
*** AttributeError: 'generator' object has no attribute 'json'
ipdb> resp.__aenter__()
<generator object CoroutineMock._mock_call.<locals>.<lambda> at 0x7effad912468>
ipdb> resp.json()
<MagicMock name='get().__aenter__().json()' id='139636593767928'>
ipdb> session
<aiohttp.client.ClientSession object at 0x7effb15548d0>
ipdb> next(resp.__aenter__())
TypeError: object MagicMock can't be used in 'await' expression

So what is proper way to mock async context manager ?

A: The asynctest hasn't received any update since 2020 and one keeps getting the following deprecation notice:
python3.9/site-packages/asynctest/mock.py:434
  python3.9/site-packages/asynctest/mock.py:434: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
    def wait(self, skip=0):

Instead MagicMock can be used for mocking the coroutine as mentioned in the documentation:

Setting the spec of a Mock or MagicMock to an async function will result in a coroutine object being returned after calling.

So you could easily use the following:
from unittest.mock import MagicMock

@pytest.mark.asyncio
async def test_download():
    mock = aiohttp.ClientSession
    mock.get = MagicMock()
    mock.get.return_value.__aenter__.return_value.status = 200
    mock.get.return_value.__aenter__.return_value.text.return_value = 'test content'

    async with aiohttp.ClientSession() as session:
        async with session.get('http://test.com') as response:
            assert response.text() == 'test content'

A: In your link, there is an edit:

EDIT: A GitHub issue mentioned in this post has been resolved and as
  of version 0.11.1 asynctest supports asynchronous context managers out
  of the box.

Since asynctest==0.11.1, it was changed, a working example is:
import random
from aiohttp import ClientSession
from asynctest import CoroutineMock, patch

async def get_random_photo_url():
    while True:
        async with ClientSession() as session:
            async with session.get('random.photos') as resp:
                json = await resp.json()
        photos = json['photos']
        if not photos:
            continue
        return random.choice(photos)['img_src']

@patch('aiohttp.ClientSession.get')
async def test_call_api_again_if_photos_not_found(mock_get):
    mock_get.return_value.__aenter__.return_value.json = CoroutineMock(side_effect=[
        {'photos': []}, {'photos': [{'img_src': 'a.jpg'}]}
    ])

    image_url = await get_random_photo_url()

    assert mock_get.call_count == 2
    assert mock_get.return_value.__aenter__.return_value.json.call_count == 2
    assert image_url == 'a.jpg'

The critical problem is that you need to correctly mock function json as by default it is a MagicMock instance. To get access to this function, you need mock_get.return_value.__aenter__.return_value.json.

A: Building on @Sraw 's answer:

@pytest.mark.gen_test
@patch('application.adapters.http_retriever.aiohttp.ClientSession.get')
async def test_get_files(mock_get):

    with open('tests/unit/sample_csv_files/Katapult_mock_response.json','r') as f:
        json_dict = json.load(f)

    mock_get.return_value.__aenter__.return_value.json = CoroutineMock()
    mock_get.return_value.__aenter__.return_value.status = 200
    mock_get.return_value.__aenter__.return_value.json.return_value = json_dict

This worked for me

A: You dont need to install any framework to test aiohttp.ClientSession
Check it out:
# Module A

import aiohttp

async def send_request():
    async with aiohttp.ClientSession() as session:
        async with session.post("https://example.com", json={"testing": True}) as response:
            if response.status != 200:
                print("Woops")
                return False

            print("YAY!")
            return True

# Module A test

import pytest
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

# Do not forget to replace `path_to_module_a` with the module that imports aiohttp
import path_to_module_a.send_request

@patch("path_to_module_a.aiohttp.ClientSession")
@pytest.mark.asyncio
async def test_should_fail_to_send_request(mock: MagicMock):
    session = MagicMock()
    session.post.return_value.__aenter__.return_value = SimpleNamespace(status=500)

    mock.return_value.__aenter__.return_value = session

    response = await send_request()

    assert response == False
    assert session.post.call_args.kwargs["json"] == {"testing": True}


text:
Q: Recovering Ubuntu after Windows Vista x64 installation
Possible Duplicate:
Repair grub mbr and /boot using ubuntu 9.04 live CD

Hi there,
how to recover Ubuntu after installing Windows Vista x64? Vista is installed on another HDD partition, however it has probably overwritten the GRUB. I don't have the Ubuntu Live CD. How to do that without the CD?
Thank you in advance for the reply!

A: Reinstall GRUB. I believe you'll need some kind of LiveCD for this though.


text:
Q: First-chance exception at 0x03f7111c in CEDel.exe: 0xC0000005: Access violation writing location 0x002e0364 I am getting a "First-chance exception at 0x03f7111c in CEDel.exe: 0xC0000005: Access violation writing location 0x002e0364." error when running my code. I am currently running in debug mode, and running on an actual Win Mobile CE 6.5.3 device that is plugged into my computer. The top of the stack (that is not disassembly) is pointing to an if statement, and I am not sure what is causing the error. The project was created in MS eMbedded C++ several years ago, and I am porting it to MS Visual Studio 2008.
The code is
CDeviceFuncCursor& curs = tempDeviceFunc.GetCursor();// added for debug checks

if (((wcscmp(_wcsupr(tempDeviceFunc.GetCursor().m_szSection), _wcsupr(INI_SERVERS_SECTION)) == 0) &&    //INI_SERVERS_SECTION == _T("Servers")
    ((wcscmp(_wcsupr(tempDeviceFunc.GetCursor().m_szVariable), _wcsupr(FTP_PRIMARY)) == 0) ||   //FTP_PRIMARY == _T("Primary")
*    (wcscmp(_wcsupr(tempDeviceFunc.GetCursor().m_szVariable), _wcsupr(SERVER_PORT)) == 0))))   //SERVER_PORT == _T("SERVERPORT")
{
    CString csValue = tempDeviceFunc.GetCursor().m_szValue;
    csValue = EncryptData(csValue.GetBuffer(csValue.GetLength()));

    WriteProfileString(tempDeviceFunc.GetCursor().m_szSection, tempDeviceFunc.GetCursor().m_szVariable, csValue.GetBuffer(csValue.GetLength()+1));
}

The line with the * is the one being pointed to by the stack.
at the break point: curs.m_szSection = "APPLICATIONCONTROL", curs.m_szVariable = "AppLanguage", curs.m_szValue == "0"
I am not sure where to look to find the error,

A: I guess you have a macro
#define SERVER_PORT _T("SERVERPORT")

in which case _T("SERVERPORT") is a const array.
You're not allowed to modify it (_wcsupr modifies its argument in-place).
Replace the macro with a variable:
TCHAR SERVER_PORT[] = _T("SERVERPORT");


text:
Q: Updating Controller and Views after adding column to Model I am new to Entity framework, so this is probably a stupid question.
I have added a new field to a Model class. I have created the migration and updated the database and this all works as expected. The new column has appeared in the SQL table.
I have manually modified the Create/Details Views (I'm guessing this isn't automatic) to include the new column. The new column is called "Level".
However, my Controller class doesn't seem to have picked up the changes. It doesn't insert the value when creating a new row. There are references to column names in the Controller class, but the new column name isn't there. E.g.
public async Task<IActionResult> Create([Bind("Id,Name")] Course course)

Is there any way to "refresh" the Controller to pick up the changes? Or will I have to manually edit the lines where the columns are named and add the new column?

A: If your view has a control bound to this new Level field and you want to pass it to the controller to write, then you will need to add it to the Bind attribute:
public async Task<IActionResult> Create([Bind("Id,Name,Level")] Course course)

While it might look like when you pass a Model to a view, and have a Form in the view that calls an action on the Controller passing that Model back, this isn't actually what happens. ASP.Net MVC is merely formatting the code in that way. Honestly this is a bit of a bad practice when using EF Entities as it trips up quite a few developers expecting that Entity references are being passed between server and view. It leads to confusing problems and is also an open door to data tampering when used incorrectly.
When the controller passes the Model to the View(), it is passing that Model to the View Renderer to compose the HTML view that will be sent to the browser. So  if you're passing a Course entity, that entity does not travel to the client, it is consumed by the Server to build the HTML.
When your Form goes to call the controller, it will automatically append any bound fields that it knows about. This will include any bound entry controls, and if there are any details that don't have edit controls bound to them, you need to use bound Hidden controls to ensure that the MVC Javascript knows to pick those up too.
If you use a Bind attribute, this tells MVC which properties coming back from a Form submit or Ajax call that you actually want to accept. If "Level" isn't in there, the value will be ignored even if passed. The View does not pass an actual entity, it will be a set of named parameters that MVC has some magic smarts to convert into a Model object based on convention.
The Action could be written as either:
public async Task<IActionResult> Create([Bind("Id,Name,Level")] Course course)

or
public async Task<IActionResult> Create(int id, string name, string level)

where in the second case you'd need to handle the creation and population of your Course entity using the values passed in.


text:
Q: Connect Flat files using java jdbc I have a problem with connecting flat files(.txt, .xml, .csv, .xls, etc...) which is existing in application it's self, using jdbc connection.
After searching I found some suggestions below.
1)xlsql
2)JDO
I tried with first one (xlsql), below is the process.
First create core java project and load the jar files which is from xlsql.
below is the code
Class.forName("com.nilostep.xlsql.jdbc.xlDriver");
final String dir = System.getProperty("user.dir")+"\\db\\xl";
conn = DriverManager.getConnection("jdbc:nilostep:excel:/"+dir);
Statement stmt = con.createStatement();
String sql = "select * from  Sheet1$";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()){
System.out.println(rs.getString(1));
}else{
System.out.println("nodata....");
}

It is saying Sheet1$ table not existing.
Please help me.

A: xlsql's principle is a little complex, it uses hsqldb or mysql as sql engines, creates related databases and tables with data from excels files, then executes queries over the database. It treats:
    directory -> database
    excel file -> schema
    sheet -> table

so It accesses a table using a schema prefix. for example:
    String sql = "select * from \"demo.xlsqly7\"";

Here "demo" is the excel file name without extension, xlsqly7 is the sheet name. In "XlSQL-Y8.zip" or "xlsql-Y7.zip" , there is an example "TestXlsql.java". I also wrote another one:
public static void main(String[] args) throws Exception {
    Class.forName("com.nilostep.xlsql.jdbc.xlDriver");
    String dir = "C:\\Temp\\xlsql-Y7";
    Connection con = DriverManager.getConnection("jdbc:nilostep:excel:"+dir);
    Statement stmt = con.createStatement();
    String sql = "select * from  \"Book1.MergedResult\"";
    ResultSet rs = stmt.executeQuery(sql);
    if(rs.next())
    {
        System.out.println(rs.getString(1));
    }
    else{
        System.out.println("nodata....");
    }

}

Another constraint is that the first row of a sheet must be column names which must start with a uppercase letter, or the sheet will be considered invalidate.
This is the best document about XLSQL: http://blog.csdn.net/ailvey/article/details/8779119, unfortunately, it is written in Chinese.


text:
Q: SQL Query causing me lack of sleep So I am revising for an exam and have struck a big rock in the SQL river (or waste ground)
I made the following tables and inserted the following data:
create table Permissions
(
    fileName VARCHAR(40),
    userID VARCHAR (16),
    type VARCHAR(10),
    startdate DATE,
    duration NUMBER (5),
    constraint Pri_key PRIMARY KEY (userID,fileName)
);

create table Files
(
    name VARCHAR(20),
    fsize INT,
    numberofpermissions INT,
    constraints PRI_KEY2 PRIMARY KEY (name)
);

create table Users
(
    id VARCHAR(20),
    password VARCHAR (20),
    constraint Pri_key3 PRIMARY KEY (id)
);

-- after all tables create:
alter table Permissions
    add constraint Forn_key FOREIGN KEY (userID) REFERENCES Users(id)
    INITIALLY DEFERRED DEFERRABLE;
alter table Permissions
    add constraint Forn_key2 FOREIGN KEY (filename) REFERENCES Files(name)
    INITIALLY DEFERRED DEFERRABLE;
insert into Permissions VALUES ('Agenda','Jones','read','19-JAN-10',30);
insert into Permissions VALUES ('Agenda','Chun','read','19-JAN-10',30);
insert into Permissions VALUES ('Agenda','Rashid','write','17-JAN-10',50);
insert into Permissions VALUES ('Finance','Chun','write','05-DEC-09',50);
insert into Permissions VALUES ('AnnualReport','Jones','write','12-DEC-09',50);
insert into Users VALUES ('Jones', 'duck');
insert into Users VALUES ('Chun', 'tiger');
insert into Users VALUES ('Adams', 'shark');
insert into Users VALUES ('Rashid', 'puma');
insert into Files VALUES ('Agenda', 32, 3);
insert into Files VALUES ('FinanceTables',645, 0);
insert into Files VALUES ('Finance', 120, 1);
insert into Files VALUES ('AnnualReport', 1205, 1);
commit;

I Am now trying to write a SQL command to display for each user who has
permissions for files of a total size of more than 50: the user's
id, the total size of all the files the user has permissions for, and
the user's password.
Here is what I have so far but when i try to add anything in to get the password, SQL+ throws up a hissy fit and there will be a hole in my screen soon!
SELECT permissions.userID, sum(fsize) AS Totalsize
FROM files, permissions
where permissions.filename = files.name
group by permissions.userid
having SUM(fsize) > 50;

A: In oracle, you need to specify the entire group by
SELECT permissions.userID, users.password, sum(fsize) AS Totalsize
FROM files, permissions, users
where permissions.filename = files.name
and users.id = permissions.userID
group by permissions.userid, permissions.password
having SUM(fsize) > 50;

This is different from MySQL where the group by can be implied, but this is more correct.

A: Join against the user table, and add the password to the group by clause:
SELECT permissions.userID, users.password, sum(fsize) AS Totalsize
FROM files, permissions, users
where permissions.filename = files.name
and users.id = permissions.userID
group by permissions.userid, users.password
having SUM(fsize) > 50;

A: Use the JOIN syntax. It complies with ANSI SQL. Joining using WHERE is an old syntax that should not be used any more.
SELECT
    u.id AS userid, u.password, SUM(f.fsize) AS Totalsize
FROM
    users u
    INNER JOIN permissions p
        ON u.id = p.userID
    INNER JOIN files f
        ON p.filename = f.name
GROUP BY
    u.id, u.password
HAVING
    SUM(f.fsize) > 50;

Note that conditions based on aggregation functions must be placed in the HAVING clause. The difference between the WHERE and the HAVING clause is, that WHERE is executed before grouping and HAVING is executed after grouping.
Also, the GROUP BY clause must contain all the expressions from the SELECT-list that don't have an aggregation function.

A: This should work:
SELECT Users.id, Users.password, Totalsize
FROM Users
     INNER JOIN
     (SELECT userId, SUM(fSize) AS TotalSize
      FROM permissions
           INNER JOIN files ON permissions.filename = files.name
      group by permissions.userid
      having SUM(fsize) > 50) t ON t.userId = Users.Id

This could be done without the inner join of course, however if you gonna need more fields this makes it easier to add them without having to add the extra fields to the group by clause.


text:
Q: How do I network a real Android device with an Emulator? What if I want to connect my Android mobile with my PC server so that my mobile can send my data (my current location) to my PC? The socket between my mobile Android and my PC (SERVER) doesn't work. Any suggestions? It only works when using the android emulator.

A: Step #1: Connect the phone to a local network via WiFi.
Step #2: Connect the PC to the same network.
Step #3: Write an app server on the PC that is listening on an IP address on that network (hint: not just localhost).

A: Another alternative using USB if you don't want to rely on your local network:

*

*configure Tethering & portable hotspot on Android

*connect the computer to the hotspot using USB

*start the PC (SERVER)

*connect the Android client

A: You should connect to IP of your PC at any free port. Port should match the one server listens on.
You can get this IP from ipconfig or ifconfig or something else (depends on OS you have).
If your PC is under NAT (doesn't have "white" IP-address, but have non-world IP, such as 192.168.whatever, 10.10.whatever) you should additionally configure network and connect to appropriate port.
You write "socket doesn't work". Can you give more info? What does your server log say? No incoming connection at all?