text:
Q: Ionic 2 Native Audio throwing error in browser I started creating an app with Ionic 2, and it was going pretty well until I attempted to add sounds. I installed the NativeAudio module according to the Ionic Framework guide, and then I added these lines of code.
In app.module.ts
import { NativeAudio } from '@ionic-native/native-audio';

In game.ts
@Component({
  selector: 'page-game',
  templateUrl: 'game.html',
})
export class GamePage {
...
constructor(public navCtrl: NavController, public alertCtrl: AlertController, public navParams: NavParams, public nativeAudio: NativeAudio) {
this.nativeAudio.preloadSimple('correctMp3', '../../assets/mp3/correct.mp3');
}
}
  guessLetter(letterIn) {
        this.nativeAudio.play('correctMp3');

    }
  }

(sorry about the formatting in advance). The code was working fine before I added in the sounds, but now it throws this error when I try to load GamePage.
    Runtime Error
    Uncaught (in promise): Error: No provider for NativeAudio! Error: No
 provider for NativeAudio! at injectionError
(http://localhost:8100/build/vendor.js:1590:86) at noProviderError
(http://localhost:8100/build/vendor.js:1628:12) at
ReflectiveInjector_._throwOrNull (http://localhost:8100/build/vendor.js:3129:19)
at ReflectiveInjector_._getByKeyDefault
(http://localhost:8100/build/vendor.js:3168:25) at ReflectiveInjector_._getByKey
(http://localhost:8100/build/vendor.js:3100:25) at ReflectiveInjector_.get
(http://localhost:8100/build/vendor.js:2969:21) at
AppModuleInjector.NgModuleInjector.get
(http://localhost:8100/build/vendor.js:3937:52) at resolveDep
(http://localhost:8100/build/vendor.js:11398:45) at createClass
(http://localhost:8100/build/vendor.js:11262:32) at createDirectiveInstance
(http://localhost:8100/build/vendor.js:11082:37)

Also
Stack
Error: Uncaught (in promise): Error: No provider for NativeAudio!
Error: No provider for NativeAudio!
    at injectionError (http://localhost:8100/build/vendor.js:1590:86)
    at noProviderError (http://localhost:8100/build/vendor.js:1628:12)
    at ReflectiveInjector_._throwOrNull (http://localhost:8100/build/vendor.js:3129:19)
    at ReflectiveInjector_._getByKeyDefault (http://localhost:8100/build/vendor.js:3168:25)
    at ReflectiveInjector_._getByKey (http://localhost:8100/build/vendor.js:3100:25)
    at ReflectiveInjector_.get (http://localhost:8100/build/vendor.js:2969:21)
    at AppModuleInjector.NgModuleInjector.get (http://localhost:8100/build/vendor.js:3937:52)
    at resolveDep (http://localhost:8100/build/vendor.js:11398:45)
    at createClass (http://localhost:8100/build/vendor.js:11262:32)
    at createDirectiveInstance (http://localhost:8100/build/vendor.js:11082:37)
    at c (http://localhost:8100/build/polyfills.js:3:13535)
    at Object.reject (http://localhost:8100/build/polyfills.js:3:12891)
    at Tab.NavControllerBase._fireError (http://localhost:8100/build/vendor.js:43003:16)
    at Tab.NavControllerBase._failed (http://localhost:8100/build/vendor.js:42991:14)
    at http://localhost:8100/build/vendor.js:43046:59
    at t.invoke (http://localhost:8100/build/polyfills.js:3:9283)
    at Object.onInvoke (http://localhost:8100/build/vendor.js:4508:37)
    at t.invoke (http://localhost:8100/build/polyfills.js:3:9223)
    at r.run (http://localhost:8100/build/polyfills.js:3:4452)
    at http://localhost:8100/build/polyfills.js:3:14076

You can view my project's structure at http://i.imgur.com/QMZ2ymI.png.

A: The problem is that you just added the import in the desired file but did not add it to the provider file.
Open up:
src/app/app.module.ts
At the top of the file import the plugin, in this case NativeAudio:
import { NativeAudio } from '@ionic-native/native-audio';
Then add the Providers section the new plugin:
providers: [
    StatusBar,
    SplashScreen,
    NativeAudio, // New provider, don't forget to add comma
    {provide: ErrorHandler, useClass: IonicErrorHandler}
]

You're all set!

A: Are you waiting for the preload promise to be resolved?
I had a lot of trouble getting sounds on Android to work.
I finally did a really simple test and this works fine:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NativeAudio } from '@ionic-native/native-audio';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  JCinfo = "start V1.1";
  JCneedLoadFlag = true;

  constructor(
      public navCtrl: NavController,
      public nativeAudio: NativeAudio,
    ) {}

  onJCbutton(){

    if(  this.JCneedLoadFlag){

      this.nativeAudio.preloadComplex('audioTag', 'assets/audio/someSound.mp3', 1, 1, 0)
      .then((data) => {
        this.JCinfo += "\npreload ok";
        this.JCneedLoadFlag = false;

        this.nativeAudio.play('audioTag')
          .then( (data)=>{
            this.JCinfo += "\nplay ok";
          }, (errData) =>{
            this.JCinfo += "\nplay err";
          })
      }, (errdata)=>{
        this.JCinfo += "\npreload err";
      });
    } else {
        this.nativeAudio.play('audioTag')
          .then( (data)=>{
            this.JCinfo += "\nplay2 ok";
          }, (errData) =>{
            this.JCinfo += "\nplay2 err";
          });
    }
  }
}

where JCinfo is output in a textarea in the html template.


text:
Q: Password Recovery: How to decrypt an md5 encrypted password?
Possible Duplicate:
Is it possible to decrypt md5 hashes?

In my website, I'm using md5 encryption for the password. So it's saving in the encrypted form in the database. For doing the password recovery, how can I decrypt the encrypted password ??
Please Help :)

A: As others described quite well, you cannot easily 'decrypt' an MD5 hash.
I guess the best way to do your password recovery is like this:

*

*A user can request password recovery
by providing his email address (it should be unique so users can be identified by email address).

*an email is sent to his address with a
link containing a unique hash (which
you have generated when sending the
email and saved it to the db).

*when the link is clicked by the user (and
of course the unique hash is checked
to be equal with the one in the db)
you can show a form which lets them
choose a different password.
Another route that some people use is to simply ask for the email address, generate a new password and send it to the user. The problem with this one is that someone who knows only your email address can request a password change. He won't know the new pass, and you will get it by email, but still it is very inconvenient for the user.

A: MD5 is a hash-based encryption. What that means, is that there is no way to get back the original value. You have created something that is a "checksum" of the original data. You can use the MD5 algorithm to encrypt something else, and then compare that to the MD5'd version of the data, but you can never get back the original.
It would be similar to me saying:  5 + 3 + 2 = 10.  The original data is 5, 3, and 2. But the "hash" is 10. There is no way to get the original data from the hash, but if someone supplies the correct input ( 5, 3, 2 ), I can hash it, and confirm that it matches hash that I have on file, 10.

A: I think MD5 is a one way hashing algorithm. What that means is that once you encrypt it, the data cannot be decrypted. (I'm sure a good hacker will disagree though)
Anyways, for passwords you can save the encrypted version of the password in the database. When a user attempts to log in, encrypt the entered password using the same MD5 algorithm, and compare the encrypted version of the password against the encrypted password stored in the database.
Once you're comfortable with this approach, you can start looking at the concept of adding salt to the hashed password.
Also, there are other hashing algorithms than just MD5. If you're using .NET, there's a bunch in the framework, such as SHA512Managed. Each one has its trade offs, such as speed to hash, security, etc. Pick one that fixes your particular problem.

A: You can't decrypt a md5 password! The only way would be to brute force it!
If you want to do password recovery make a random string witch will be sent to the user by email (or any other way) and set as a md5'd password... Just an idea
EDIT:
Why would you encrypt a password to keep it safe if you can decrypt it? Makes no sense! -> You could the basically leave the password unencrypted!

A: It's not easy, but you're best bet would be to use a rainbow table as the MD5 has does have vulnerabilities.
There are several online versions, which you may or may not be able to trust (or work).

A: You can try to search in a MD5 hash database like:

*

*http://www.md5-hash.com/

*http://www.md5decrypter.com/

*others....

Chances are small but you can try.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVN partial branch I'm new to SVN so this could be an easy question.
We have a "trunk" with 1st level directories:
10 <-- documents
20 <-- source code, db scripts, ...
30 <-- documents
40 <-- referenced 3rd party library-es

I made a "develop" branch from the "trunk".
In "develop" we change our source code and after testing it we merge it to "trunk".
The problem in that in directories "10" and "30" are stored *.doc files that are not needed for development so it is REQUIRED that "develop" branch doesn't have those directories.
The solution should still:

*

*allow "svn update" on root folder of "develop" working copy, (20 and 40)

*that update should not re-create
directories 10 and 30 and

*of course merging "develop" to "trunk" should NOT delete 10 or 30 in "trunk".

EDIT:
I forgot to mention that "source code" is not only in 20. There are referenced dll-s and build scripts etc. that are also on 1st level directory, lets say 40.

A: What you want to do is create a copy of "20" somewhere in your svn tree, which you can merge back and forth with. A common structure is
repo
---> trunk
    ---> 10
    ---> 20
    ---> 30
---> branches
    ---> sandboxes
        ---> develop <branch of 20>
---> tags

When you want to update "develop", you either create a new branch of "20" under sandboxes or perform a merge from 20 to develop. When you want the changes in "develop" back in your trunk you merge the other way. Your developers should check out a copy of "develop" (or create their own branches based on "develop")

A: afaik you can't do it with the repository structure you currently have.
I suggest you restructure your repository, so 10 & 20, 40 & the other code related assets are moved under a new 1st level folder. This way you avoid this situation, and simplify being able to grab just the code related assets.

A: If I read your question correctly, this is a simple matter of using svn copy to copy only the desired directories into a branch -- basically, a combination of answers from Mike Kushner and Ivan Krechetov. I think, however, it might be easier to understand after running through the steps yourself, so the rest of this post will create a sample repository and show the copies and merges.
I'm going to assume that you're using the "standard" repository layout, which at the top level has three sub-directories, trunk, branches, and tags. And that your 10, 20, 30, and 40 directories are under trunk. In other words:
trunk
    10
    20
    30
    40
branches
tags

And, as Mike pointed out, your goal will be to have a structure that looks like this:
trunk
    10
    20
    30
    40
branches
    sandbox
        20
        40
tags

It's unclear from your posting (at least as-of the current edit), but you may have a directory structure in which 10, 20, et al are at the top level. In this case, you'll need to create a new top-level directory, which I'll call dev, so that your overall repository looks like the following:
10
20
30
40
dev
    20
    40

Note that you cannot create dev under 20. Well, physically you can, but you're almost guaranteed to break your build when doing so.
OK, so let's walk through an example, in which we create a new repository and put some files in it. You have to be able to run the svnadmin command (which you should be able to do, unless you have a paranoid sysadmin). So pick a temporary directory, and execute the following commands (I'm running Linux; if you're running Windows the commands will be the same, but you'll need to put a Windows-specific path in the REPO variable):
svnadmin create temp.repo
REPO="file://`pwd`/temp.repo"
svn co $REPO temp

This creates a new (empty) repository, and checks out a working copy of it. The second line needs some explanation: it simply creates the repository URL from the current directory. In my workspace directory, the URL looks like this:
file:///home/kgregory/Workspace/temp.repo

OK, now that you've got a working copy, let's create the sample directory structure and some files:
cd temp
svn mkdir trunk
svn mkdir branches
svn mkdir tags
svn commit -m "standard repo structure"

pushd trunk
svn mkdir 10
svn mkdir 20
svn mkdir 30
svn mkdir 40
svn commit -m "example sub-project structure"

echo "this doesn't change" > 10/dontchange.txt
svn add 10/dontchange.txt
echo "this does change" > 20/change.txt
svn add 20/change.txt
svn status
svn commit -m "example files"
popd

At this point we have the sample directories and two files in them. Here's the output from find, excluding subversion's hidden directories:
temp, 531> find . | grep -v svn
.
./tags
./trunk
./trunk/10
./trunk/10/dontchange.txt
./trunk/30
./trunk/20
./trunk/20/change.txt
./trunk/40
./branches

Next step is to create the sandbox directory, and make copies of the two directories that are going to be in it:
svn mkdir branches/sandbox
pushd branches/sandbox
svn copy ${REPO}/trunk/20 .
svn copy ${REPO}/trunk/40 .
svn commit -m "make development branch"
popd

This is the important part: I creating the branch and copies in my working directory, as a copy from the repository. Normally, you just copy trunk into a child of branches, using svn copy with two repository arguments. That doesn't work here, because we want only two children of trunk.
After doing this, my working copy looks like this:
temp, 539> find . | grep -v svn
.
./tags
./trunk
./trunk/10
./trunk/10/dontchange.txt
./trunk/30
./trunk/20
./trunk/20/change.txt
./trunk/40
./branches
./branches/sandbox
./branches/sandbox/20
./branches/sandbox/20/change.txt
./branches/sandbox/40

At this point, you'd normally check out the development branch into a new working directory and work there. So I'll do that (after a cd back to my Workspace directory):
svn co ${REPO}/branches/sandbox sandbox
cd sandbox

And now make some changes:
vi 20/change.txt
svn commit -m "changed on branch"

OK, now it's time to merge back to the trunk. So go back to the workspace, and check out just the trunk:
svn co ${REPO}/trunk trunk
cd trunk

And merge from the sandbox. The merge process is described in the Subversion docs:
svn merge -r 4:5 ${REPO}/branches/sandbox
svn status

That last command should show you that only the file 20/change.txt was affected by the merge. Since you didn't copy the 10 or 30 directories into the branch, they won't be touched by the merge.

A: Ideally then you should branch at a lower level. i.e. branch 20 not trunk. That way you're only branching the content that should be branched. i.e. that you want branched.

A: You can achieve that by making only the source code subdirectory of your working copy point to its branch.
svn cp http://example.com/svnrepo/trunk/source_code http://example.com/svnrepo/branches/development/source_code

cd ./source_code
svn sw http://example.com/svnrepo/branches/development/source_code

Do the changes, commit. Then, let's merge to the trunk:
svn sw http://example.com/svnrepo/trunk/source_code
cd ..
svn merge -r [start_rev]:HEAD http://example.com/svnrepo/branches/development/source_code ./source_code

Review to make sure all's fine:
svn diff | less

And then commit.
Done.

A: We do something like this:
-repo: Assemblies
--SomeAssembly
---Current
---v1.0
---v1.1
-repo: Source
--trunk
---Code
---Assemblies (external from Assemblies repo)
--branches
---v1.0
----Code
----Assemblies (external from Assemblies repo)
--Documents

In this example, the 3rd party assemblies have their own repository. This way you aren't maintaining different versions in each branch and trunk. As a side note, the latest version of any assembly is duplicated in the "Current" folder for each assembly. This allows the assembly to be updated without having to update references in all your projects. This may not be an issue in your domain, but it was a big pain in ours.
Also note that the documents are at the same level in the hierarchy as trunk and the branches. This way those files don't get duplicated. If this is not an option, those can be externaled as well, which would allow them to be present in the trunk and branches without being separately source controlled.

A: The way you structure your project, along with the docs dir restrictions, doesn't fit with SVN's model out of the box.
Some ideas:

*

*Move the docs dir outside trunk, and add it as an svn:external

*Move the docs dir outside trunk, and have a build script combine trunk and the docs dir

*Merge using a script (instead of a direct svn merge), and have the script enforce the rules

A: From your comment:

We want to prevent modification of documents in 10 and 30. They should be modified only in the trunk.

Have you considered using svn:externals in the develop branch for 10 and 30?  Relative referencing from root using ^/ would probably be a good approach.
So whilst 10, 20, 30 and 40 would be accessible on the branch, 10 and 30 are still referenced from trunk.  You can then define your authorization needs as required.

repo
  ..-> trunk
  ....-> 10
  ....-> 20
  ....-> 30
  ....-> 40
  ..-> branches
  ....-> develop
  ......-> 10 (lives on trunk, svn:externals ^/trunk/10)
  ......-> 20 (lives on branch, merge to trunk)
  ......-> 30 (lives on trunk,  svn:externals ^/trunk/30)
  ......-> 40 (lives on branch, merge to trunk)


text:
Q: Sign iOS Flutter application in Azure Pipelines I can't sign my Flutter project when archiving to ipa file on Azure Pipelines.
This is my build pipeline setup:

*

*Certificate get and built from Apple Developper program;

*Provisioning profile from  Apple Developper program;

*The Flutter build script is a copy of this one (no signing);

*Launch of xcodebuild archive to get a signed ipa.

I tried manual signing and automatic signing.
With manual signing
    /usr/bin/xcodebuild -sdk iphoneos -configuration Release -workspace ..../ios/Runner.xcworkspace -scheme Runner archive CODE_SIGN_STYLE=Manual CODE_SIGN_IDENTITY=iPhone Distribution: My Name (MYTEAMID) PROVISIONING_PROFILE=guid-of-my-provisioning-profile PROVISIONING_PROFILE_SPECIFIER= | /usr/local/lib/ruby/gems/2.6.0/bin/xcpretty -r junit --no-color

## RESULT IS ERROR 65
    error: Pods-Runner does not support provisioning profiles. Pods-Runner does not support provisioning profiles, but provisioning profile com.blabla.myapp has been manually specified. Set the provisioning profile value to "Automatic" in the build settings editor. (in target 'Pods-Runner' from project 'Pods')
    error: shared_preferences does not support provisioning profiles. shared_preferences does not support provisioning profiles, but provisioning profile com.blabla.myapp has been manually specified. Set the provisioning profile value to "Automatic" in the build settings editor. (in target 'shared_preferences' from project 'Pods')

With Automatic signing
    /usr/bin/xcodebuild -sdk iphoneos -configuration Release -workspace .../ios/Runner.xcworkspace -scheme Runner archive CODE_SIGN_STYLE=Automatic DEVELOPMENT_TEAM=MYTEAMID | /usr/local/lib/ruby/gems/2.6.0/bin/xcpretty -r junit --no-color

## RESULT IS ERROR 65
    error: No profiles for 'com.blabla.myapp' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.blabla.myapp'. Automatic signing is disabled and unable to generate a profile. To enable automatic signing, pass -allowProvisioningUpdates to xcodebuild. (in target 'Runner' from project 'Runner')

With Automatic signing and -allowProvisioningUpdates
    /usr/bin/xcodebuild -sdk iphoneos -configuration Release -workspace .../ios/Runner.xcworkspace -scheme Runner archive -allowProvisioningUpdates CODE_SIGN_STYLE=Automatic DEVELOPMENT_TEAM=MYTEAMID | /usr/local/lib/ruby/gems/2.6.0/bin/xcpretty -r junit --no-color

## RESULT IS ERROR 65
    error: There are no accounts registered with Xcode. Add your developer account to Xcode (in target 'Runner' from project 'Runner')
    error: No profiles for 'com.blabla.myapp' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.blabla.myapp'. (in target 'Runner' from project 'Runner')

Any idea? And first, should I use Automatic or Manual signing?
EDIT 1
I tried with azure-pipelines.yaml found here and I still have the error:
Starting: Xcode archive and sign
==============================================================================
Task         : Xcode
Description  : Build, test, or archive an Xcode workspace on macOS. Optionally package an app.
Version      : 5.151.2
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/build/xcode
==============================================================================
/usr/bin/xcodebuild -version
Xcode 11.1
Build version 11A1027
/usr/bin/xcodebuild -sdk iphoneos -configuration Release -workspace /Users/runner/runners/2.160.1/work/1/s/ios/Runner.xcworkspace -scheme Runner clean analyze archive -verbose CODE_SIGN_STYLE=Manual CODE_SIGN_IDENTITY=iPhone Distribution: XXXXXX (XXXXXXX) PROVISIONING_PROFILE=dd325087-6f6c-467b-93e2-a8c2446711e3 PROVISIONING_PROFILE_SPECIFIER=
Build settings from command line:
    CODE_SIGN_IDENTITY = iPhone Distribution: XXXXXX (XXXXXXX)
    CODE_SIGN_STYLE = Manual
    PROVISIONING_PROFILE = dd325087-6f6c-467b-93e2-a8c2446711e3
    PROVISIONING_PROFILE_SPECIFIER =
    SDKROOT = iphoneos13.1

note: Using new build system

** CLEAN SUCCEEDED **

note: Using new build system
note: Planning build
note: Constructing build description
error: Pods-Runner does not support provisioning profiles. Pods-Runner does not support provisioning profiles, but provisioning profile com.example.blabla has been manually specified. Set the provisioning profile value to "Automatic" in the build settings editor. (in target 'Pods-Runner' from project 'Pods')
error: shared_preferences does not support provisioning profiles. shared_preferences does not support provisioning profiles, but provisioning profile com.example.blabla has been manually specified. Set the provisioning profile value to "Automatic" in the build settings editor. (in target 'shared_preferences' from project 'Pods')

** ANALYZE FAILED **

note: Using new build system
note: Planning build
note: Constructing build description
error: shared_preferences does not support provisioning profiles. shared_preferences does not support provisioning profiles, but provisioning profile com.example.blabla has been manually specified. Set the provisioning profile value to "Automatic" in the build settings editor. (in target 'shared_preferences' from project 'Pods')
error: Pods-Runner does not support provisioning profiles. Pods-Runner does not support provisioning profiles, but provisioning profile com.example.blabla has been manually specified. Set the provisioning profile value to "Automatic" in the build settings editor. (in target 'Pods-Runner' from project 'Pods')

** ARCHIVE FAILED **

PS

*

*I can build and archive an a Macbook with Xcode ;

*I can build and archive on AppCenter with this script (but all my other pipelines are on DevOps and I would like to keep one tool for CI/CD).

SOLUTION
As suggested by Levi, I edited the generated Podfile and forced a commit of it.
PS: no need to update install/uninstall cocoapods, package on Azure Pipelines is today on the latest version 1.8.4.

A: You can use flutter install task and flutter build instead of to run the bash scripts. Check it here.
If your project needs cocoapods, you may need to add Cocoapods task to to your pipeline. Please check the example provided by Microsoft to learn more about how to build xcode apps.
For troubleshooting the profiles not fund error, you can check if the carthage lib was correctly configured into xcode projet. You can also try the solutions provided here.
Update:
For pods-runner not support error, Please try to add below to your pod file.
  post_install do |installer|
      installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
          config.build_settings['EXPANDED_CODE_SIGN_IDENTITY'] = ""
          config.build_settings['CODE_SIGNING_REQUIRED'] = "NO"
          config.build_settings['CODE_SIGNING_ALLOWED'] = "NO"
        end
      end
    end

And add below script to install the latest version cocoapods before building
    echo "uninstalling all cocoapods versions"
    sudo gem uninstall cocoapods -ax
    echo "installing cocoapods version latest"
    sudo gem install cocoapods --pre

For more information you can check this thread.


text:
Q: Json stringify in JS and decoding in php js
var sim_list=[];
var simvalue = $('input[name="simnamecbx"]:checked').each(function(){
    var sim_name=this.value.split(" ")[0];
    console.log("simname:",sim_name);
    sim_list.push({
        sim_name
    });
);
console.log(sim_list);
var simulation_list = JSON.stringify(sim_list);
$.ajax({ url: 'addprogram.php',
     data: {addpgmname:addprogname, addpgmcomp:addprogcomp, addpgmdate:addprogdate, simselvalue:simulation_list},
     type: 'post',
     dataType: 'json',
     success: function(output){
         var a = output;
         console.log(a);
     }
});

php
$simvalue = json_decode($_POST["simselvalue"],true);
foreach($simvalue as $key => $value) {
    print_r($value);
}

Question
When I execute the above php I get the values as
Array
(
    [0] => Array
        (
            [sim_name] => 12
        )

    [1] => Array
        (
            [sim_name] => 13
        )

    [2] => Array
        (
            [sim_name] => 14
        )

)

But I want the result to be like 12, 13, 14 which can be inserted into mysql table. Please explain how to parse this array that I get from javascript.

A: I think that the problem is that you are pushing an object with sim_name on to your array instead of the actual value. This actually only works in ES6 compatible browsers which makes your error invisible.
The problem is this part in your javascript code:
sim_list.push({
    sim_name
});

In ECMAScript 6 this is the equivalent of the following:
sim_list.push({
    sim_name: sim_name
});

Thus you are pushing an object with the sim_name property set to the number (e.g. 12, 13, 14).
What I think that you want to do is the following:
sim_list.push(sim_name)

This will push only the number onto the array.
All together now:
JS
var sim_list = []

$('input[name="simnamecbx"]:checked').each(function () {
  var sim_name = this.value.split(' ')[0]
  sim_list.push(sim_name)
})

var data = {
  addpgmname: addprogname,
  addpgmcomp: addprogcomp,
  addpgmdate: addprogdate,
  simselvalue: JSON.stringify(sim_list)
}

$.ajax({
  url: 'addprogram.php',
  data: data,
  type: 'post',
  dataType: 'json',
  success: function (output) {
    console.log(output)
  }
})

PHP
$simvalue = json_decode($_POST["simselvalue"]);

print("The selected values was: " . implode($simvalue, ", "));

A: Easiest way:
$data = json_decode($_POST["simselvalue"], true) // true = associative array

foreach($data as $key => $value) {
    // database query
}


text:
Q: Cascade drop down list in excel(dynamically) I have two set of excel values which I am generating dynamically named "category" and "value list". I am assigning those values for two named ranges and use them in a drop down list.(data validation list).
"value list" is depends on the selection of category. I want to create a casacde drop down based on those dynamic values . I found several posts but there are static lists.
Here is one post I found cascade drop downs
Can anybody suggests a good way to do this
Thanks


text:
Q: Correct Format in Passing Dynamic Text in JSON String for Excel Headers I have a variable that translates dynamically based on the selected language of the user. I am trying to replace the text for the column headers of the excel file being downloaded but I cannot get the correct format where in I can replace the hardcoded headers text with my variable. Can anyone help me with this? Thanks!
Here's the return inside  my json to excel function
    var newJson = this.props.users_list.map(function (obj) {
          return {
                "Name": /^[-@=+]/.test(obj.name) ? "\'" + obj.name : obj.name,
                "Contact": /^[-@=+]/.test(obj.contact) ? "\'" + obj.contact : obj.contact,
                ....
                }
}

I want to replace the headers "Name" and "Contact" here with the variable lang.name and lang.contact which are declared like this after my imports:
const toolLanguage = {
    name: "Name",
    contact: "Contact"
};
const lang = Utilities.translateLang(toolLanguage);

I've tried these formats but I'm only getting typing errors:
    lang.name : /^[-@=+]/.test(obj.name) ? "\'" + obj.name : obj.name,
    lang.contact : /^[-@=+]/.test(obj.contact) ? "\'" + obj.contact : obj.contact,

    {lang.name} : /^[-@=+]/.test(obj.name) ? "\'" + obj.name : obj.name,
    {lang.contact} : /^[-@=+]/.test(obj.contact) ? "\'" + obj.contact : obj.contact,

A: This format works for me:
  var newJson = this.props.users_list.map(function (obj) {
               let objTemp = {};
               objTemp[lang.name] = /^[-@=+]/.test(obj.name) ? "\'" + obj.name : obj.name,
               objTemp[lang.contact] = /^[-@=+]/.test(obj.contact) ? "\'" + obj.contact : obj.contact
      return objTemp;
            });


text:
Q: Two Persistence Unit in one Persistence.xml We created some libraries that all our projects will use, this libraries will provide the basic functionality of all our systems (login, some manage, etc). But the application itself could use another database.
What we did was to create the Persistence.xml with two persist units. And package all the core library entities in a jar called "LN-model.jar" and all of the entities of out test app in "App-model.jar". But for some reason we still obtain the following message.

Could not resolve a persistence unit corresponding to the persistence-context-ref-name [x.x.x.x.listener.InicializadorListener/em] in the scope of the module called [gfdeploy#/Users/zkropotkine/WORK/SeguridadCore/dist/gfdeploy/SeguridadCore-war_war]. Please verify your application.

Here's our Persistence.xml
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

<persistence-unit name="x" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/x</jta-data-source>
    <jar-file>App-model.jar</jar-file>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    </properties>
</persistence-unit>

<persistence-unit name="y" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/y</jta-data-source>
    <jar-file>LN-model.jar</jar-file>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
</persistence-unit>

By the way we put the Persistence.xml in a jar, that we add to our Enterprise Project (EAR).

A: The problem is that the JPA does not know which is the persistence unit to use. when you have only one persistence unit this problem does not occur. To fix do the following:
You need to specify a persistence unit : @PersistenceContext(unitName="...") in the Ejb that do not have

A: You can add the annotations:
@PersistenceUnit(name = "x")
EntityManagerFactory entityManagerFactory;

@PersistenceContext(unitName = "y")
EntityManager entityManager;

Or you can create it manually:
EntityManagerFactory emfA = Persistence.createEntityManagerFactory("x", properties);
EntityManagerFactory emfB = Persistence.createEntityManagerFactory("y", properties);

For more details, please see the following link: https://docs.oracle.com/html/E25034_01/usingmultipledbs.htm
is very useful, to me helped me!


text:
Q: Difference of Cooley Tukey-Gentleman Sande and DIT-DIF Newbie here.
I want to ask for NTT Implementation.
We know there are several options like Cooley-Tukey, Gentleman-Sande, and Stockholm.
Also, there's something called Decimation in Time (DIT) and Decimation in Frequency (DIF).
As long as I know, the DIC and DIT have different purposes and different Butterfly Unit structures. As the picture follows,
DIC - DIF Butterfly Unit
I'm not sure the difference about Cooley Tukey and Gentleman Sande, but I know one of them should have normal order input and later on bit-reversed order for the output.
Does anyone can explain it more clearly the difference between them ? Also Can I use DIF also DIT for Cooley Tukey ?


text:
Q: add xml namespace to child element i wanted to added namespace to child element bt it is of no use..
i wanted the xml to look like this
final.xml
<sc:BusinessDataElementCatalog xmlns:sc="http://sctax.org/scits/oc-adapter">
  <sc:ScitsDataElementCatalog sc:Version="648" sc:ElementCount="18" sc:Created="2013-04-08T11:44:21" sc:CreatedBy="SYSTEM" sc:LastModified="2013-04-08T11:44:21" sc:ModifiedBy="SYSTEM">
    <sc:ScitsDataElement xmlns:sc="http://sctax.org/scits/oc-adapter" sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="FrontNopaDataEntryDesc" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true" />
    <sc:ScitsDataElement xmlns:sc="http://sctax.org/scits/oc-adapter" sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="FrontNopaGLAcctCode" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true" />
    <sc:ScitsDataElement xmlns:sc="http://sctax.org/scits/oc-adapter" sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="FrontNopaDataEntryCode" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true" />
    <sc:ScitsDataElement xmlns:sc="http://sctax.org/scits/oc-adapter" sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="FrontNopaGLAcctName" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true" />
    <sc:ScitsDataElement xmlns:sc="http://sctax.org/scits/oc-adapter" sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="FrontJournalTypeSection" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true" />
    <sc:ScitsDataElement xmlns:sc="http://sctax.org/scits/oc-adapter" sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="FrontNopaPenaltyAmount" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true" />
  </sc:ScitsDataElementCatalog>
</sc:BusinessDataElementCatalog>

bt all i could manage is this xml
result.xml
<sc:BusinessDataElementCatalog  xmlns:sc="http://sctax.org/scits/oc-adapter">
  <sc:ScitsDataElementCatalog  sc:Version="648" sc:ElementCount="18" sc:Created="2013-04-08T11:44:21.000000" sc:CreatedBy="2013-04-08T11:44:21" sc:LastModified="2013-04-08T11:44:21.000000" sc:ModifiedBy="2013-04-08T11:44:21">
    <sc:ScitsDataElement sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="BackNopaTotBalance" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true">
  </sc:ScitsDataElement>
    <sc:ScitsDataElement sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="BackNopaTotPmntsCredits" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true">
  </sc:ScitsDataElement>
    <sc:ScitsDataElement sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="BackNopaTotLiability" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true">
  </sc:ScitsDataElement>
    <sc:ScitsDataElement sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="BackPeriodEndDateSection" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true">
  </sc:ScitsDataElement>
    <sc:ScitsDataElement sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="BackNopaGLAcctName" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true">
  </sc:ScitsDataElement>
    <sc:ScitsDataElement sc:Action="Add" sc:ElementDataSource="ITS" sc:ElementName="BackNopaDataEntryCode" sc:MultiLine="false" sc:ElementNamePrefix="its_" sc:ElementSource="ITS" sc:DataType="string" sc:Formatting="NotFormatted" sc:Shared="true" sc:Mandatory="false" sc:Editable="true" sc:MailTo="false" sc:ContextType="Entity" sc:ElementUse="ITS" sc:CaseEnabled="true">
  </sc:ScitsDataElement>
</sc:ScitsDataElementCatalog >
</sc:BusinessDataElementCatalog >

and this is my query
SELECT XMLELEMENT("sc:BusinessDataElementCatalog ",
XMLATTRIBUTES('http://sctax.org/scits/oc-adapter' AS "xmlns:sc")
, B.XML )
FROM
    (SELECT
        XMLELEMENT ("sc:ScitsDataElementCatalog " ,
        XMLATTRIBUTES( MAX(C.REVISION) AS "sc:Version" ,
        COUNT(*) AS "sc:ElementCount" ,
        MIN(C.CREATED_DTTM) AS "sc:Created",
        '2013-04-08T11:44:21' AS "sc:CreatedBy" ,
        MAX(C.UPDATED_DTTM) AS "sc:LastModified" ,
        '2013-04-08T11:44:21' AS "sc:ModifiedBy" ) ,
            XMLAGG(
                XMLELEMENT("sc:ScitsDataElement",
                    XMLATTRIBUTES ('http://sctax.org/scits/oc-adapter' AS "xmlns:sc",
                      CASE
                        WHEN ( CATALOG.version_on_insert > 630 )
                        THEN 'Add'
                        ELSE 'Update'
                      END AS "sc:Action" ,
                      DATASOURCE.CODE AS "sc:ElementDataSource",
                      CATALOG.ELEMENT_NAME AS "sc:ElementName" ,
                      CASE
                        WHEN ( CATALOG.multiline_flag = 1 )
                        THEN 'true'
                        ELSE 'false'
                      END AS "sc:MultiLine" ,
                      'its_' AS "sc:ElementNamePrefix" ,
                      DATASOURCE.CODE AS "sc:ElementSource" ,
                      LOWER(DATATYPE.CODE) AS "sc:DataType" ,
                      FORMATTYPE.CODE AS "sc:Formatting"  ,
                        CASE
                           WHEN ( CATALOG.shared_element_flag = 1 ) THEN 'true'
                      ELSE 'false'
                         END as "sc:Shared"  ,
                      CASE
                           WHEN ( CATALOG.mandatory_flag = 1 ) THEN 'true'
                      ELSE 'false'
                         END as "sc:Mandatory"  ,
                      CASE
                           WHEN ( CATALOG.editable_flag = 1 ) THEN 'true'
                      ELSE 'false'
                         END as "sc:Editable"  ,
                      CASE
                           WHEN ( CATALOG.mail_to_flag = 1 ) THEN 'true'
                      ELSE 'false'
                         END as "sc:MailTo"  ,
                      context.code as "sc:ContextType"  ,
                      'ITS' as "sc:ElementUse"  ,
                      CASE
                           WHEN ( CATALOG.case_enabled_flag = 1 ) THEN 'true'
                      ELSE 'false'
                         END AS "sc:CaseEnabled"  ,
                      CATALOG.default_value as "sc:DefaultValue"
                      )
                  )
              )
          )AS xml
    FROM ITS_OC_DATA_ELEMENT_CATALOG CATALOG
    JOIN ITS_OC_DATA_ELEMENT_CATALOG C
    ON c.OC_DATA_ELEMENT_CATALOG_KEY=CATALOG.OC_DATA_ELEMENT_CATALOG_KEY
    JOIN r_oc_element_datasource dataSource
    ON CATALOG.oc_element_datasource_key = dataSource.oc_element_datasource_key
    JOIN r_oc_element_datatype datatype
    ON CATALOG.oc_element_datatype_key = datatype.oc_element_datatype_key
    JOIN r_oc_context_type context
    ON CATALOG.oc_context_type_key = context.oc_context_type_key
    JOIN r_oc_text_format_type formatType
    ON CATALOG.OC_TEXT_FORMAT_TYPE_KEY = FORMATTYPE.OC_TEXT_FORMAT_TYPE_KEY
    WHERE CATALOG.REVISION             > 630
    ) B ;

is it possible for sc:ScitsDataElement to have namespace..how can i acchieve it in this query..


text:
Q: Annotator 2.0.0-alpha.3 not working in touch devices I am using annotator js(2.0.0-alpha.3) in my application it works well in desktop and in touch devices it is not working.
I see in documentation when we use 1.2 version we can use a touch plugin but for version 2.0.0 we dont have any plugin but we have native mobile support.
And also in documentation I can see for 2.1 version these are the changes available
https://github.com/openannotation/annotator/blob/master/doc/roadmap.rst
The main goals for this release, which we aim to ship by Jan 1, 2016 (with a major feature freeze on Nov 15):

*

*Support for selections made using the keyboard

*Support in the core for annotation on touch devices

*Support for multiple typed    selectors in annotations

*Support for components that resolve    ('reanchor') an annotation's
selectors into a form suitable for    display in the page

But I could nt see any 2.1 version in github so wanted to know whether we have updated information on the same.


text:
Q: Get specifics ids in IndexedDB I have an IndexedDB table with a lot of records, I need to access to specifics records and I have The keys, for Example [1,4,6,7,10,25]. I need to make a query and get only these records, but checking out the documentation. All IDBKeyRange methods are about get "ranges" and not something like "in" clausule in SQL.
Which is the correct way to get this ?
Searching on google I read several post about use "getAll" method instead of cursors, but I didn't find how can I access to specifics keys, only the "only" method, bus is for one id not more.


text:
Q: KSH scripting: -z and -a I have the below condition:
 if [ ! -z $DateC -a "$DateC"=="$DateJ" ]

If had like to know what -z and -a means.  I don't understand what this condition verifies.  I have searched the net for -a and -z but I don't really get what it does.  Any help, pls?

A: Check man test for this:
   -z STRING
          the length of STRING is zero
   EXPRESSION1 -a EXPRESSION2
          both EXPRESSION1 and EXPRESSION2 are true

So this checks if the length of $DateC is not zero and $DateC and $DateJ are equal.
if [ ! -z $DateC -a "$DateC"=="$DateJ" ]
#      ^^^^^^^^^ ^^
#         |     AND
#         |
#      length of string is zero
#
#    ^^^^^^^^^^^^^^^^^^^^^^^^^^
#    length of string is NOT zero

See an example:
$ r=hello
$ s=hello
$ [ "$r"=="$s" ] && echo "yes" || echo "no"
yes

With the other condition:
$ t=""
$ if [ ! -z "$t" -a "$r"=="$s" ]; then echo "yes"; else echo "no"; fi
no
$ t=a
$ if [ ! -z "$t" -a "$r"=="$s" ]; then echo "yes"; else echo "no"; fi
yes

Finally,

Note that POSIX recommends the use of && and || with the
  single bracket notation over -a and -o, so if you are writing
  portable code go for the first notation, otherwise the second and skip
  the third, especially since it can get awkward and hard to read if you
  need to group expressions. – Adrian Frühwirth (source)


text:
Q: Django site cant be reached I run the server in c9 (django workspace). There were no errors and it said

Starting development server at http://127.0.0.1:8000//.

However, when i open this site it says

This site can't be reached
   127.0.0.1 refused to connect.

Can anyone help me fix this issue

A: 127.0.0.1 is your local computer, not the c9 instance. The docs refer to a unique URL for each app, like: http://<workspacename>-<username>.c9users.io:8081
So, try using runserver like this: python manage.py runserver $IP:$PORT
You can then look in your browser tab for the server address that you can see your app running on, which will be similar to the one above. You'll use that when testing instead of localhost or 127.0.0.1.
Check out the Django guide on their site  for more details.

A: In the documentation says that you use a URL they give to you (not localhost) to access the server

Use the Share button on the top to figure out the URLs of running Application and the Preview.

See https://docs.c9.io/docs/run-an-application#section--pre-view-your-application


text:
Q: Silverlight - Rotated TextBlock width problem I have the following grid:
    <Grid Background="LightGray" x:Name="ProgrammPoolTextGrid">
        <TextBlock x:Name="tbLeft"
                   Margin="0"
                   Text="PROGRAMMPOOL"
                   TextWrapping="NoWrap"
                   Width="100"
                   Height="94"
                   RenderTransformOrigin="0.5,0.5"
                   HorizontalAlignment="Left"
                   UseLayoutRounding="False"
                   d:LayoutRounding="Auto" >
            <TextBlock.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="-90"/>
                    <TranslateTransform/>
                </TransformGroup>
            </TextBlock.RenderTransform>
        </TextBlock>
    </Grid>

I need just a 40px width TextBlock, but if I change the width of the TextBlock or of the Grid, the text will cut. Any idea?

A: What happens is that the transform is done after the measure and layout operations are finished so it takes the measures of the original control, it can be fixed using the LayoutTransformer Control which is included in the silverlight toolkit.
Here is an example: Using the Silverlight Toolkit LayoutTransformer Control for Angled Column Header Text (from MSDN Blogs)


text: Q: openshift ruby can not recognize rails console? I have a simple code  and it runs okay in my localhost, but when I push it to open shift server it can not read the data I have added in rails controller as like title or email etc, and shows nothing, when there is no syntax error ?


text:
Q: Count characters in each line of a file? Any tips on how to count the amount of characters in each line of a text file, to then compare them using python?

A: It would be helpful to have an idea of what the end goal of your code is. What information do you want to gain from comparing the number of characters on a line? I would have written this as a comment, but it's not yet an option for me since I just joined.
If you're completely lost and don't know where to begin, here are some general bits of code to get you started (this is using Python 3.x):
file = open("YourFileName.txt", "r")
stringList = file.readlines()

The first line will open (read, hence the "r") the file in question. The second line of code goes through each line in the file and assigns them to a variable I called stringList. stringList is now a list, in which each element is a string corresponding to one line of your text file.
So,
print(stringList)

should return
['line0', 'line1', 'line2', 'line3', etc...]

It's possible that stringList could look like
['line0\n', 'line1\n', 'line2\n', 'line3\n', etc...]

depending on how your file is formatted. In case you didn't know, the '\n' is a newline character, equivalent to hitting enter on the keyboard.
From there you can create another list to hold the length of each line, and then loop through each element of stringList to store the lengths.
lengthList = []
for line in stringList:
    lengthList.append(len(line))

len(line) takes the number of characters in a string and converts it to the equivalent integer value. Your lengthList will then contain how many characters are on each line, stored as ints. If there are '\n's, you may want to use len(line) - 1, depending on what you want to do with the lengths.
I hope this is helpful; I can't help with the comparisons until you provide some code and explain more specifically what you want to accomplish.


text:
Q: Using foreach to loop more than two list I'm trying to loop five list by merging them.
I know that this works fine
var zipped = letters.Zip(numbers, Tuple.Create);

 foreach (var tuple in zipped)
 {
     Console.WriteLine(tuple.Item1);
     Console.WriteLine(tuple.Item2);
 }

but i'm wondering I can use that same method, but with more list included.
Let's say I have the list numbers, letters, words, pictures and songs
How whould that loop look like then?

A: The simplest approach would probably be to reimplement Zip yourself multiple times, e.g.
public static IEnumerable<Tuple<T1, T2>> ZipTuple<T1, T2>(
    this IEnumerable<T1> source1,
    IEnumerable<T2> source2)

public static IEnumerable<Tuple<T1, T2, T3>> ZipTuple<T1, T2, T3>(
    this IEnumerable<T1> source1,
    IEnumerable<T2> source2,
    IEnumerable<T3> source3)

public static IEnumerable<Tuple<T1, T2, T3, T4>> ZipTuple<T1, T2, T3, T4>(
    this IEnumerable<T1> source1,
    IEnumerable<T2> source2,
    IEnumerable<T3> source3,
    IEnumerable<T3> source4)

The implementation will be tedious, but it's fairly simple to do.
Then you can just call:
var query = numbers.ZipTuple(letters, words, pictures, songs);

I'd probably implement each independently from scratch, but you could do it with one call to the "previous" ZipTuple and one call to Zip in each case, e.g.
public static IEnumerable<Tuple<T1, T2, T3>> ZipTuple<T1, T2, T3>(
    this IEnumerable<T1> source1,
    IEnumerable<T2> source2,
    IEnumerable<T3> source3)
{
    return source1
        .ZipTuple(source2)
        .Zip(source3, (t1, extra) => Tuple.Create(t1.Item1, t1.Item2, extra));
}

public static IEnumerable<Tuple<T1, T2, T3, T4>> ZipTuple<T1, T2, T3, T4>(
    this IEnumerable<T1> source1,
    IEnumerable<T2> source2,
    IEnumerable<T3> source3,
    IEnumerable<T4> source4)
{
    return source1
        .ZipTuple(source2, source3)
        .Zip(source4, (t1, extra) => Tuple.Create(t1.Item1, t1.Item2, t1.Item3, extra));
}

The direct version would look something like this:
public static IEnumerable<Tuple<T1, T2, T3, T4>> ZipTuple<T1, T2, T3, T4>(
    this IEnumerable<T1> source1,
    IEnumerable<T2> source2,
    IEnumerable<T3> source3,
    IEnumerable<T4> source4)
{
    // TODO: Extract a separate public method from the implementation
    // method and perform eager validation for nullity
    using (var iterator1 = source1.GetEnumerator())
    using (var iterator2 = source2.GetEnumerator())
    using (var iterator3 = source3.GetEnumerator())
    using (var iterator4 = source4.GetEnumerator())
    {
        while (iterator1.MoveNext() && iterator2.MoveNext() &&
               iterator3.MoveNext() && iterator4.MoveNext())
        {
            yield return Tuple.Create(
                iterator1.Current,
                iterator2.Current,
                iterator3.Current,
                iterator4.Current);
        }
    }
}

A: Maybe I am just stupid, but a for loop would usually do very good (assuming all lists have the same length):
for (int i = 0; i < numbers.Count; i++)
{
    var n = numbers[i];
    var l = letters[i];
    var w = words[i];
    var p = pictures[i];
    var s = songs[i];

    // use your variables

    Console.WriteLine($"number  = {n}");
    Console.WriteLine($"letter  = {l}");
    Console.WriteLine($"word    = {w}");
    Console.WriteLine($"picture = {p}");
    Console.WriteLine($"song    = {s}");
}

A: Unfortunately in C# you can't define a generic method with as many generic arguments as you want. So you would have to define your Zip function for any number of generic types.
For instance, for 3 generic arguments:
public static IEnumerable<T> Zip<T1,T2,T3> (this IEnumerable<T1> e1, IEnumerable<T2> e2, IEnumerable<T3> e3)
{
    var i1 = e1.GetEnumerator();
    var i2 = e2.GetEnumerator();
    var i3 = e3.GetEnumerator();

    // warning: this implementation does not fail if the enumerable do not
    // have the same sizes, it stops when the shortest one is enumerated
    while (i1.MoveNext() && i2.MoveNext() && i3.MoveNext()) {
        yield return Tuple.Create(i1.Current,i2.Current,i3.Current);
    }
}

A: You can do it in a several ways
public static IEnumerable<T> Zip<T>(this List<T> source, params IEnumerable<T>[] collections)
    {
        source.AddRange(collections.SelectMany(collection => collection));
        return source;
    }

Or:
var concat = letters.Concat(numbers).Concat(songs).Concat(pictures);

Or:
var union = letters.Union(numbers).Union(songs).Union(pictures);

Or if you want Tuples, you can do this:
letters.Zip(numbers, Tuple.Create).Zip(pictures, (x, y) => Tuple.Create(x.Item1, x.Item2, y)).Zip(songs, Tuple.Create)

Or
public static IEnumerable<Tuple<T, T>> ZipTuple<T>(this List<Tuple<T, T>> source, IEnumerable<T> collection )
public static IEnumerable<Tuple<T, T>> ZipTuple<T>(this List<Tuple<T, T, T>> source, IEnumerable<T> collection)
public static IEnumerable<Tuple<T, T>> ZipTuple<T>(this List<Tuple<T, T, T, T>> source, IEnumerable<T> collection)
etc...


text:
Q: Carefully mending "Objects are not aligned" error in python, with matrices In my recent exercise, I were to write a function that get a matrix A and a number k, and gives the k-th approximation to A's eigenvalues, using the approximation formulas of Rayleigh Quotient Iteration. I wrote the following function, made sure the first iteration is okay, but then the second get as error, and I don't know how to maintain a matrix or a vector the way there are. I am frustrated and would really appreciate any kind of help.
def RayleighQuotientItreation(A,k):
   import math
   import numpy as np
   I=np.matrix(np.identity(A.shape[0]))
   b=np.random.rand(A.shape[0])
   b=math.pow(normal(b),-1)*b
   u=(np.dot(b,(np.dot(A.T,b)).T))[0,0]
   for i in range(0,k):
      b, u=(np.dot(np.linalg.inv((A-  u*I)).T,b))*math.pow(normal((np.dot(np.linalg.inv((A-u*I)),b)).T),-1), (np.dot((np.dot(b.T,A)),b))[0,0]
   return u


text:
Q: Using Magnifying Glass Outside the Form Good afternoon! There is a form (Lens), which serves as a magnifying glass (inside the form). I need to get rid of the TargetForm property so that the form (Lens) works without binding to the form, as an independent control. What code to replace it with, please tell me.

Code For Main_Form
private void button1_Click(object sender, EventArgs e) {
    new Lens_Form() { TargetForm = this }.Show(this);
    Cursor.Hide();
}

Code For Lens_Form
public partial class Lens_Form : Form {
    public Form TargetForm { get; set; }
    public new float Scale { get; set; }

    private Bitmap tmpBmp;

    public Lens_Form() {
        InitializeComponent();

        // Drawing the Ellipse
        GraphicsPath path = new GraphicsPath();
        path.AddEllipse(ClientRectangle);
        Region = new Region(path);

        // Set Scale
        Scale = 2; // 2-4-6-8
    }

    protected override void OnPaint(PaintEventArgs e) {
        Point pos = TargetForm.PointToClient(Cursor.Position);
        Location = new Point(Cursor.Position.X - Width / 2, Cursor.Position.Y - Height / 2);

        Rectangle screenRectangle = TargetForm.RectangleToScreen(TargetForm.ClientRectangle);
        int dY = screenRectangle.Top - TargetForm.Top;
        int dX = screenRectangle.Left - TargetForm.Left;

        e.Graphics.TranslateTransform(Width / 2, Height / 2);
        e.Graphics.ScaleTransform(Scale, Scale);
        e.Graphics.TranslateTransform(-pos.X - dX, -pos.Y - dY);

        if (tmpBmp != null) e.Graphics.DrawImage(tmpBmp, 0, 0);
    }

    // Timer
    private void Main_Timer_Tick(object sender, EventArgs e) {
        tmpBmp = new Bitmap(TargetForm.Size.Width, TargetForm.Size.Height);
        TargetForm.DrawToBitmap(tmpBmp, new Rectangle(0, 0, TargetForm.Width, TargetForm.Height));
        Invalidate();
    }
}

A: You need to scale up and work with bigger boundaries, the screen's instead of the Form's. Capture the screen instead of the Form by the Graphics.CopyFromScreen method.
Here's a working example with some extras using the same approach.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class Lens_Form : Form
{
    private readonly Timer timer;
    private Bitmap scrBmp;
    private Graphics scrGrp;
    private bool mouseDown;

    public Lens_Form() : base()
    {
        SetStyle(
            ControlStyles.OptimizedDoubleBuffer |
            ControlStyles.Opaque |
            ControlStyles.UserPaint |
            ControlStyles.AllPaintingInWmPaint, true);
        UpdateStyles();

        FormBorderStyle = FormBorderStyle.None;
        ShowInTaskbar = false;
        TopMost = true;
        Width = 150;
        Height = 150;

        timer = new Timer() { Interval = 55, Enabled = true };
        timer.Tick += (s, e) => Invalidate();
    }

    public int ZoomFactor { get; set; } = 2;
    public bool HideCursor { get; set; } = true;
    public bool AutoClose { get; set; } = true;
    public bool NearestNeighborInterpolation { get; set; }

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);

        var gp = new GraphicsPath();
        gp.AddEllipse(0, 0, Width, Height);
        Region = new Region(gp);

        CopyScreen();
        SetLocation();

        Capture = true;
        mouseDown = true;
        if (HideCursor) Cursor.Hide();
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);

        if (e.Button == MouseButtons.Left)
        {
            mouseDown = true;
            if (HideCursor) Cursor.Hide();
        }
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        Invalidate();
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        base.OnMouseUp(e);

        mouseDown = false;
        if (HideCursor) Cursor.Show();
        if (AutoClose) Dispose();
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);

        if (e.KeyCode == Keys.Escape) Dispose();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (mouseDown) SetLocation();
        else CopyScreen();

        var pos = Cursor.Position;
        var cr = RectangleToScreen(ClientRectangle);
        var dY = cr.Top - Top;
        var dX = cr.Left - Left;

        e.Graphics.TranslateTransform(Width / 2, Height / 2);
        e.Graphics.ScaleTransform(ZoomFactor, ZoomFactor);
        e.Graphics.TranslateTransform(-pos.X - dX, -pos.Y - dY);
        e.Graphics.Clear(BackColor);

        if (NearestNeighborInterpolation)
        {
            e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
            e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;
        }

        if (scrBmp != null) e.Graphics.DrawImage(scrBmp, 0, 0);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            timer.Dispose();
            scrBmp?.Dispose();
            scrGrp?.Dispose();
        }
        base.Dispose(disposing);
    }

    private void CopyScreen()
    {
        if (scrBmp == null)
        {
            var sz = Screen.FromControl(this).Bounds.Size;

            scrBmp = new Bitmap(sz.Width, sz.Height);
            scrGrp = Graphics.FromImage(scrBmp);
        }

        scrGrp.CopyFromScreen(Point.Empty, Point.Empty, scrBmp.Size);
    }

    private void SetLocation()
    {
        var p = Cursor.Position;

        Left = p.X - Width / 2;
        Top = p.Y - Height / 2;
    }
}

A caller in the main Form:
private void SomeButton_MouseDown(object sender, MouseEventArgs e)
{
    var f = new Lens_Form()
    {
        Size = new Size(150, 150),
        AutoClose = true,
        HideCursor = true,
        ZoomFactor = 2,
        NearestNeighborInterpolation = false
    };
    f.Show();
}

Notes

*

*The SetStyle method is called in the constructor to apply some useful styles in this context to the control. To takeover the painting routine, reduce the flickering, and prevent painting the background.

*Override the OnShown method to get the size set by the caller and set the region, take a screenshot, and set the Form's location.

*Override the mouse methods to apply the properties and refresh the view.

*Override the OnPaint method to move the Form while the mouse left button is pressed otherwise recopy the screen. This is to give you two options, magnifying while dragging the Form or while moving the mouse with no buttons pressed if you disable the AutoClose property. For the transformation part, use the current Cursor.Position and the screen coordinates of the Form (instead of the main From) to do the math.

*

*Lastly, override the Dispose method to clean up.

Demo


text:
Q: Ffmpeg pipe stream glitch I want to process ffmpeg raw video stream, and I can't understand why this code produces glitches. What's wrong?
ffmpeg -i in.mp4 -f image2pipe -pix_fmt rgb24 -vcodec rawvideo - |
ffmpeg -f rawvideo -vcodec rawvideo -s 1980x1080 -pix_fmt rgb24 -r 24 -i - -an out.avi

Thanks!

A: For rawvideo streams, you have to have the correct size set, so you need to change your invocation of ffmpeg to:
ffmpeg -i in.mp4 -f image2pipe -pix_fmt rgb24 -vcodec rawvideo - |
ffmpeg -f rawvideo -vcodec rawvideo -s 1920x1080 -pix_fmt rgb24 -r 24 -i - -an out.avi

This is assuming that your in.mp4 file is a Full HD file.


text:
Q: Java movement in opposite direction cancels itself for a brief moment I am trying to make a smooth movement in Java
and after watching some videos on YouTube,
I recreated it,
but found a bug that was missed in the video.
If you quickly press a key for moving in opposing directions after letting go of the first key
(example: you move right,
let go of right,
then press "left"
there is a small stagger).
Does anyone have any ideas for this?
This is mine Main class where the listeners are:
public void keyPressed(KeyEvent e)
    {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D)
        {
            p.setVelX(5);
        }
        else if(key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A)
        {
            p.setVelX(-5);
        }
        else if(key == KeyEvent.VK_UP || key == KeyEvent.VK_W)
        {
            p.setVelY(-5);
        }
        else if(key == KeyEvent.VK_DOWN || key == KeyEvent.VK_S)
        {
            p.setVelY(5);
        }
        else if(key == KeyEvent.VK_SPACE && !isShooting)
        {
            isShooting = true;
            c.addBullet(new Bullet(p.getX(), p.getY(), tex));
        }

    }

    public void keyReleased(KeyEvent e)
    {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D)
        {
            p.setVelX(0);
        }
        else if(key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A)
        {
            p.setVelX(0);
        }
        else if(key == KeyEvent.VK_UP || key == KeyEvent.VK_W)
        {
            p.setVelY(0);
        }
        else if(key == KeyEvent.VK_DOWN || key == KeyEvent.VK_S)
        {
            p.setVelY(0);
        }
        else if(key == KeyEvent.VK_SPACE)
        {
            isShooting = false;
            c.addBullet(new Bullet(p.getX(), p.getY(), tex));
        }
    }

And this is mine Player class:
public void tick()
    {
        x+=velX;
        y+=velY;

    }

    public double getX()
    {
        return x;
    }

    public double getY()
    {
        return y;
    }

    public void setX(double x)
    {
        this.x = x;
    }

    public void setY(double y)
    {
        this.y = y;
    }

    public void setVelX(double velX)
    {
        this.velX = velX;
    }

    public void setVelY(double velY)
    {
        this.velY = velY;
    }

A: You can store the keys ifPressed flags somewhere and handle the keyRelease for a direction if only opposite direction is released as well like:
if((key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D) && !isLeftPressed)
{
    p.setVelX(0);
    isRightPressed = false;
}

A: After testing some answers, I found a solution:
public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D)
    {
        isRight = true; //if the key is pressed
        p.setVelX(5);
    }
    else if(key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A)
    {
        isLeft = true; //if the key is pressed
        p.setVelX(-5);
    }

}

public void keyReleased(KeyEvent e)
{
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D)
    {
        isRight = false;
        if(!isLeft) p.setVelX(0); //if you are not going the other direction stop
    }

}


text:
Q: Nokogiri XML builder - save options I am building XML with Nokogiri with the option of not having empty tags:
doc.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS)

It indeed works for removing empty tags, however passing this option to to_xml removes all of my indentation, new line characters etc.
Is there a way to tell Nokogiri to same with NO_EMPTY_TAGS but keeping the rest of the defaults?
Help is kindly appreciated!

A: You can perform an or operation on your options' bits.
doc.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS)

This will apply the defaults of AS_XML and the additional setting of NO_EMPTY_TAGS


text:
Q: Dynamically importing commands. (ES6) I am trying to import classes dynamically when they are required.
The following code works;
import TestCommand from "./commands/TestCommand.js"; //At top of the file

And in a function;
let test = new TestCommand();
console.log(test.getName());

And the TestCommand.js;
import Command from "./Command.js";

export default class TestCommand extends Command {
    constructor() {
        super();
        this.name = "Test";
    }

    getName() {
        return this.name;
    }

    execute() {

    }
}

However, if I attempt to accomplish the same thing within a function, like so;
async function loadCommand(command) {
    let TestCommand = await import("./commands/TestCommand.js");
    let test = new TestCommand();
    console.log(test.getName());
}

I get an error;
(node:14264) UnhandledPromiseRejectionWarning: TypeError: TestCommand is not a constructor
Any suggestions on how I could accomplish this?


text:
Q: Dynamically updating QLabel - pyqt I'm having a bit of an issue. I'm trying to make a monitoring software that monitors a few voltages and other things. I'm using QT 4 Designer and pyqt to make my UI.
My code is structured like this (each one of these is a module):
Click go button ---> start hub ----> connect to device and return an array of info ---> use info and display appropriate values on to various QLabels.
I am setting the QLabels using self.label.setText(data in here).
The problem I have is now I'm trying to make the go button start a loop that repeatedly calls the start hub module (which in turn will grab information from the device, then call a module that prints that information to the QLabels) every 4 seconds or so.
As a test, I called the function 3-4 times in a row with a time.sleep(4) in between. I found that the UI only updates AFTER the last call to start hub.
I'm pretty sure that the issue is that the UI only updates when nothing is processing. But I'm not really sure how to force all the QLabels to update after each iteration. I've tried self.label.repaint() but that didn't do anything.
Can anybody help?

A: What I'm guessing is that you probably put all tasks(3-4 times hub module call, time.sleep and QLabels setText) into that UI update function, instead of doing that you should wrap the long-running tasks into a separate thread:
import threading

def LongRunningTask(self):
    for i in range(4):
        hub_module_call
        time.sleep(4)
        self.label.setText

def OnButton(self, event):
    # Click go button
    thread = threading.Thread(target=self.LongRunningTask)
    thread.start()


text:
Q: breaking on unhandled exceptions in pydev/gae i am using pydev to develop a google app engine application. i followed the steps mentioned here to configure pydev debugger to break on unhandled exception. i could get it to work on a sample pydev project, but when i try the same steps in my pydev gae project, it doesn't work and gives following error:

pydev debugger: warning: psyco not
  available for speedups (the debugger
  will still work correctly, but a bit
  slower) pydev debugger: starting
  ...
  Traceback (most recent call last):
  File "c:\program
  files\google\google_appengine\google\appengine\tools\dev_appserver.py",
  line 3858, in _HandleRequest
      self._Dispatch(dispatcher, self.rfile, outfile, env_dict)   File
  "c:\program
  files\google\google_appengine\google\appengine\tools\dev_appserver.py",
  line 3792, in _Dispatch
      base_env_dict=env_dict)   File "c:\program
  files\google\google_appengine\google\appengine\tools\dev_appserver.py",
  line 580, in Dispatch
      base_env_dict=base_env_dict)   File "c:\program
  files\google\google_appengine\google\appengine\tools\dev_appserver.py",
  line 2918, in Dispatch
      self._module_dict)   File "c:\program
  files\google\google_appengine\google\appengine\tools\dev_appserver.py",
  line 2822, in ExecuteCGI
      reset_modules = exec_script(handler_path, cgi_path,
  hook)   File "c:\program
  files\google\google_appengine\google\appengine\tools\dev_appserver.py",
  line 2702, in ExecuteOrImportScript
      exec module_code in script_module.dict   File
  "C:\Users\siddjain\workspace\rfad\src\main.py",
  line 1, in
      import pydevd ImportError: No module named pydevd

my debug configuration for gae project is like this:

the sample pydev project where it works is like this and am following same pattern in my gae project:
import pydevd

def f(x,y):
    z = y/x;
    return z;

def main():
    pydevd.set_pm_excepthook()
    print f(0,0)

if __name__ == '__main__':
    main()

the run config for test project is like this:

the pydevd.py module is under C:\eclipse\plugins\org.python.pydev.debug_2.0.0.2011040403\pysrc. Although this path is not included in the pythonpath for test project, the breaking works in test. i also tried including this path in pythonpath of gae project to see if that fixes my problem, but it didn't

A: Its still not fixed although following steps got rid of No module named pydevd error:
1. Create a symlink to C:\eclipse\plugins\org.python.pydev.debug_2.0.0.2011040403\pysrc:
src>mklink /d debugger C:\eclipse\plugins\org.python.pydev.debug_2.0.0.2011040403\pysrc
2. Put an empty __init__.py file in C:\eclipse\plugins\org.python.pydev.debug_2.0.0.2011040403\pysrc. i learnt this from some google link that i can't find now.
3. In source code:
import debugger.pydevd as pydevd
after these steps its able to import pydevd, but still doesn't break on uncaught exception.
The development server runs your application on your local computer for testing your application. The server simulates the App Engine datastore, services and sandbox restrictions (hence step 1). although i don't understand why we need to import pydevd since its pydevd who's running our application in the first place!
In the Run->Debug Configurations->Interpreter tab if I click on "see resulting command line..."
C:\Python25\python.exe -u
C:\eclipse\plugins\org.python.pydev.debug_2.0.0.2011040403\pysrc\pydevd.py
--vm_type python --client 127.0.0.1 --port 0 --file "c:\program
files\google\google_appengine\dev_appserver.py"
The PYTHONPATH that will be used is:
C:\eclipse\plugins\org.python.pydev_2.0.0.2011040403\PySrc\pydev_si...


text:
Q: is this density $f(x;\theta) = (1/\theta) x^{\theta -1} $ an exponential family? does anyone have experience to answer, is this density function:
$$f(x;\theta) = (1/\theta) x^{\theta -1} $$  for $0<x<1$ and $\theta>0$
an exponential family?
and what is the kind of distribution for that function?

A: It is a $\mathrm{Beta}(\theta,1)$.
If $\theta$ is integer, you can think it is the density of the max of $\theta$ IID uniform $[0,1]$ rvs.
Sorry previous statement was wrong: also Wikipedia
"The exponential families include many of the most common distributions, including the normal, exponential, gamma, chi-squared, beta,"
You can write the pdf as:
$$ f(x;\theta) = \theta^{-1}\cdot \exp\left( (\theta-1)\log(x)\right) $$


text:
Q: Copy only the required content from the text file to Excel using Python I have a huge data in text file consisting of details like Date, College name, Year of Passing also it contains Name and Unique id of students as shown below. Also the text file is not formatted and it contains lot of data.
Group list of all the students
5 June 2020/KCT/2015 Group BRD Rahul e34 Pradeep e44 Venkat r45 Azhar t54
6 June 2020/BCT/2012 Group ZRD Akash e14 Pavan e24 Vipul r15 Asad t14
7 June 2020/KBN/2014 Group KRD Fairoz e45 Kumar e55 Akshay e44 Vivek e99 etc

When i run a python code, I need the output in a excel/csv sheet where it displays only Name (Column1) and Unique id (Column2) row by row. Basically in the excel sheet i want only names and unique ids to be displayed in Excel sheet as shown below only i need names and unique id to be displayed. I do not need other data in the excel sheet.
Rahul    e34
Pradeep  e44
Venkat   r45
Azhar    t54
Akash    e14
Pavan    e24
Vipul    r15
Asad     t14
Fairoz   e45
Kumar    e55
Akshay   e44
Vivek    e99

This is what i have tried
import pandas as pd
df = pd.read_csv("C:\Users\PMishra\Desktop\Document.txt", sep='\t' )
df.to_csv('C:\Users\PMishra\Desktop\Demo.csv')

When i run this it will just copy all the contents from text file to excel sheet. I want output in a excel/csv sheet where it displays all Names (Column1) and Unique ids (Column2) row by row. I am new to python (Spyder). How to get only names and ids in column1 and column2 respectively?

A: Your first row must be the name of the columns, then you can show only the two columns with the name:
dfnew = df[["namecolum1","namecolum1"]]

dfnew.to_csv('C:\Users\PMishra\Desktop\Demo.csv')

A: You can load only the selected columns by calling read_csv() with the usecols argument, see the Documentation.
# this would load only column 0, 1, and 2
# you can use column names too: ['col0', 'col1', 'col2']
dummy_example = pandas.read_csv('path_to/your_file.csv', usecols=[0, 1, 2])

However, in your case I would do it without pandas;
input_file = 'path_to/input_file.txt'
output_file = 'path_to/output_file.csv'

# open both files, output in "append" mode
with open(input_file, 'r') as file, open(output_file, 'a+') as out_file:
    for line in file.readlines():

       try:
            # split at 'Group'
            line = line.split('Group')[1]

            # split and select after Group name
            line = line.split()[1:]

        except:
            # no 'Group' or no data thereafter
            # skip to the next loop
            continue

        # create name-id pairs
        name_id = list(zip(line[2::2], line[1::2]))

        for tup in name_id:
            # make comma separated string
            string = ','.join(tup) + '\n'

            # append to the outfile
            out_file.write(string)

Output file;
Pradeep,e34
Venkat,e44
Azhar,r45
Pavan,e14
Vipul,e24
Asad,r15
Kumar,e45
Akshay,e55
Vivek,e44
Pradeep,e34
Venkat,e44
Azhar,r45
Pavan,e14
Vipul,e24
Asad,r15
Kumar,e45
Akshay,e55
Vivek,e44


text:
Q: How to fix this code? It writes to file the first argument, why not the second? I am working on this code to automate "copy-paste" by reading from an access table and write to excel sheet.
Different values from access table, needs to be written in a particular cells on excel sheet.
My problem is that the code works by reading and writing the first value, but not the second++ values.
The first value is correctly written on E15 in Excel, but the second value which is supposed to be written on cell E16 is not written, Why?
Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"

Application.ScreenUpdating = False

Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")

cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(14, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

TargetRange.Offset(15, 4).CopyFromRecordset rs

 Application.ScreenUpdating = True

    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

End Sub

I dont get any error messages, the code runs, but the output is not complete.

A: Try this:
range(cells(15,4), cells(15,3+rs.Fields.Count)).CopyFromRecordset rs

A: Here is an edit to your original code that should work. There was no need to call the first Exit Sub. The second was also unnecessary since you did not have any error-handling code.
Also, you do not need to close the connection or discard rs until the end.
Sub HentData()

Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
Dim Sum As Double

DBFullName = "C:\saga_effekt_Nidaros_2017_tiltak.mdb"
Application.ScreenUpdating = False
Set TargetRange = Sheets("1.3 Persontransportmodell").Range("A1")

Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\saga_effekt_Nidaros_2017_tiltak.mdb;"

Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'sum'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(14, 4).CopyFromRecordset rs
Application.ScreenUpdating = True

On Error Resume Next
rs.Close
On Error GoTo 0

rs.Open "SELECT [VERDI] FROM [saga_trafikantnytte] WHERE [REISEMIDDE] = 'tog' AND [VARIABEL] = 'referansetrafikk'", cn, , , adCmdText

For intColIndex = 0 To rs.Fields.Count - 1
    'TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(15, 4).CopyFromRecordset rs
Application.ScreenUpdating = True

On Error Resume Next
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
On Error GoTo 0

End Sub


text:
Q: Spring SpEL when using a GenericXmlApplicationContext? I'm having a problem getting SpEL to work when loading some Spring XML configuration explicitly into a GenericXmlApplicationContext object.
Any help you can give would be greatly appreciated.
Here's my POM file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>minimal</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
       <version.spring>3.2.6.RELEASE</version.spring>
    </properties>
    <dependencies>
       <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${version.spring}</version>
       </dependency>
       <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${version.spring}</version>
       </dependency>
    </dependencies>
</project>

And here's Spring XML config file:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <bean id="defaultPerson" class="java.lang.String">
        <constructor-arg value="World!" />
    </bean>
    <bean id="greeter" class="com.example.Greeter">
        <property name="person" value="#{ getObject('specificPerson') != null ? getObject('specificPerson') : defaultPerson }"/>
    </bean>
</beans>

And finally, my Java code
public class Greeter {
    private String person;

    public String sayHello() {
        return String.format("Hello %s", this.person);
    }

    public void setPerson(String person) {
        this.person = person;
    }
}

public class Main {

    public static void main(String[] args) {
        GenericApplicationContext parentContext = new GenericApplicationContext();

                parentContext.getBeanFactory().registerSingleton("specificPerson", "Dave");

        GenericXmlApplicationContext xmlContext = new GenericXmlApplicationContext();
        xmlContext.setParent(parentContext);

        // Load the beans
        xmlContext.load("xmlContext.xml");

        // GenericXmlApplicationContext lazy loads singletons by default and we need them instantiated.
        xmlContext.getBeanFactory().preInstantiateSingletons();

        Greeter greeter = (Greeter) xmlContext.getBean("greeter");

        System.out.println(String.format("Greeter says: [%s]", greeter.sayHello()));
    }
}

I was hoping to see
Greeter says: [Hello Dave]
but instead I see:

Greeter says: [Hello #{ getObject('specificPerson') != null ? getObject('specificPerson') : defaultPerson }]

Any idea why?  Your help is greatly appreciated - thanks!

A: Turns out I needed to add calls to refresh().
Adding a call to parentContext.refresh() and xmlContext.refresh() after object construction fixed the issue.  Hope someone else finds this to be helpful!


text:
Q: Design pattern to reduce cyclomatic complexity
I have to send invoices to cutomers through the related customer's API.
Each customer chooses how to be contacted (email, fax, sms...).
My problem is that each time I add a new "contact type" I increase the cyclomatic complexity of my script.
Here is my code :
<?php

interface ExternalApi
{
    public function sendByEmail();
    public function sendByFax();
    public function sendBySMS();
    // more sending modes ...
}

class Api1 implements ExternalApi
{
    public function sendByEmail()
    {
        echo __CLASS__." sending email
\n";
    }

    public function sendByFax()
    {
        echo __CLASS__." sending fax
\n";
    }

    public function sendBySMS()
    {
        echo __CLASS__." sending SMS
\n";
    }
}

class Customer
{
    public const EMAIL = 'email';
    public const FAX = 'fax';
    public const SMS = 'sms';
    public const EMAIL_AND_FAX = 'email_and_fax';
    public const PHONE = 'phone';
    public const PLANE = 'plane';
    public const BOAT = 'boat';
    public const SATELITE = 'satelite';
    public const CAB = 'cab';
    // more contact types...

    public ?string $contactType;
}

class Invoice
{
    public Customer $customer;

    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }
}

class InvoiceSender
{
    private ExternalApi $api;

    public function __construct(ExternalApi $api)
    {
        $this->api = $api;
    }

    public function send(Invoice $invoice)
    {
        switch($invoice->customer->contactType) {
            case Customer::EMAIL :
                $this->api->sendByEmail();
                break;
            case Customer::FAX :
                $this->api->sendByFax();
                break;
            case Customer::SMS :
                $this->api->sendBySMS();
                break;
            case Customer::EMAIL_AND_FAX:
                $this->api->sendByEmail();
                $this->api->sendByFax();
                break;
            // more cases ...
        }
    }
}

$customer = new Customer();
$customer->contactType = Customer::EMAIL_AND_FAX;
$invoice = new Invoice($customer);
$api = new Api1();
$invoiceSender = new InvoiceSender($api);
$invoiceSender->send($invoice);

As you can see the switch statement of InvoiceSender::send is increased each time I add a new "contact type".
Do you know which design pattern could solve this problem ?

A: Create an interface like SendInvoiceInterface with a send and a shouldSend method. Then create 3 implementations:

*

*EmailInvoiceSender

*FaxInvoiceSender

*SMSInvoiceSender
Next inject these all into your InvoiceSender as an array. Then instead of the switch-case you can loop over all the senders and 'ask' them if they shouldSend. If that evaluates to true you can call send on them.
This way the logic stays inside each sender itself instead of the growing switch-case.

A: Thank you guys for your advices.
Your suggestion about using an array with all the services inside brings me to another solution :
<?php

interface ExternalApi
{
    public function getSendingModes();
}

class Api1 implements ExternalApi
{
    public function getSendingModes()
    {
        return [
            Customer::EMAIL => fn() => $this->sendByEmail(),
            Customer::FAX => fn() => $this->sendByFax(),
            Customer::SMS => fn() => $this->sendBySMS(),
            Customer::EMAIL_AND_FAX => function() {
                $this->sendByEmail();
                $this->sendByFax();
            },
        ];
    }

    private function sendByEmail()
    {
        echo __CLASS__." sending email
\n";
    }

    private function sendByFax()
    {
        echo __CLASS__." sending fax
\n";
    }

    private function sendBySMS()
    {
        echo __CLASS__." sending SMS
\n";
    }
}

class Customer
{
    public const EMAIL = 'email';
    public const FAX = 'fax';
    public const SMS = 'sms';
    public const EMAIL_AND_FAX = 'email_and_fax';
    public const PHONE = 'phone';
    public const PLANE = 'plane';
    public const BOAT = 'boat';
    public const SATELITE = 'satelite';
    public const CAB = 'cab';
    // more contact types...

    public ?string $contactType;
}

class Invoice
{
    public Customer $customer;

    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }
}

class InvoiceSender
{
    private ExternalApi $api;
    private array $sendingModes;

    public function __construct(ExternalApi $api)
    {
        $this->api = $api;
        $this->sendingModes = $api->getSendingModes();
    }

    public function send(Invoice $invoice)
    {
        $sendingMode = $this->sendingModes[$invoice->customer->contactType] ?? null;
        if (null === $sendingMode) {
            throw new RuntimeException("API ".get_class($this->api)." doesn't have sending mode ".$invoice->customer->contactType);
        }
        $sendingMode();
    }
}

$customer = new Customer();
$customer->contactType = Customer::EMAIL_AND_FAX;
//$customer->contactType = Customer::EMAIL;
//$customer->contactType = Customer::BOAT;
$invoice = new Invoice($customer);
$api = new Api1();
try {
    $invoiceSender = new InvoiceSender($api);
    $invoiceSender->send($invoice);
} catch (Exception $ex) {
    echo $ex->getMessage()."\n";
}

I change the ExternalApi interface in order to retreive an array of sending modes.
Doing so, each API is aware of its own sending modes and so each API don't need to implement sending mode that they don't handle.
Each value of the array is an anonymous function which trigger the private methods of the API class.
Also I don't have to write extra classes for each sending modes.


text:
Q: AttributeError and TypeError in KivyMD (Python) I got this Error when running my KivyMD app. I'm new to this field and don't know to resolve it and I have no any idea about it. But I want to prevent from this Error. I have tried many ways from the Internet. But nothing was succed. Who can resolve this Issue? Please...
.kv
MDScreen:
    name: "welcome"
    MDFloatLayout:
        md_bg_color : 1, 1, 1, 1
        Carousel:
            id: carousel
            on_current_slide: app.current_slide(self.index)
            MDFloatLayout:
                Image:
                    source: "Assets/1.png"
                    pos_hint: {"center_x": .5, "center_y": .6}
                MDLabel:
                    text: "1"
                    pos_hint: {"center_y": .087}
            MDFloatLayout:
                Image:
                    source: "Assets/2.png"
                    pos_hint: {"center_x": .5, "center_y": .6}
                MDLabel:
                    text: "2"
                    pos_hint: {"center_y": .087}

.py
class DiaryApp (MDApp):
    def build(self):
        screen_manager = ScreenManager()
        screen_manager.add_widget(Builder.load_file('kv/Diary.kv'))
        return screen_manager

    def on_start(self):
        carousel = self.root.ids.carousel
        carousel.loop = True
        Clock.schedule_interval(carousel.load_next, 3.0)

    def current_slide(self, index):
        pass

    def next(self):
        self.root.ids.carousel.load_next(mode="next")

DiaryApp().run()

Error
 Traceback (most recent call last):
   File "kivy\properties.pyx", line 961, in kivy.properties.ObservableDict.__getattr__
 KeyError: 'carousel'

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "D:\Kusal\Python\Projects\venv\Projects\Diary\Diary.py", line 47, in <module>
     DiaryApp().run()
           .
           .
           .
   File "D:\Kusal\Python\Projects\venv\Projects\Diary\Diary.py", line 22, in next
     self.root.ids.carousel.load_next(mode="next")
   File "kivy\properties.pyx", line 964, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

A: The problem is that you are trying to access the carousel id through the root ids, but that id is defined under the MDScreen, which is not the root. The fix is to access it through the MDScreen where it is defined:
def on_start(self):
    welcome_screen = self.root.get_screen('welcome')
    carousel = welcome_screen.ids.carousel
    carousel.loop = True
    Clock.schedule_interval(carousel.load_next, 3.0)


text:
Q: Translate mouse coordinates to a 3D plan I'm building some kind of drag and drop app in javascript/jquery (DOM based, not canvas).
The idea is to be able to drag divs on a 3D scene (a div rotated in 3D).
It works on a 2D plan, the problem is when I rotate the scene in 3D, the objects position doesn't reflect the actual mouse position, but the coordinates translated in 3D
Illustrated exemple :

EXEMPLE ON JSFIDDLE
I want the objects moving relative to the absolute position of the mouse.
I calculate the mouse position like this :
document.addEventListener(gestureMove, function (event) {
  if (mouseDown == true) {
  event.preventDefault();
  moveX = (event.pageX - $('#scene').offset().left);
  moveY = (event.pageY - $('#scene').offset().top);
}

#scene {
  width: 1000px;
  height: 1000px;
  -webkit-transform-style: preserve-3d;
  -webkit-transform: rotateX( 35deg );
}

An early solution was to calculate the difference between the mouse position and the object based on the initial position, and adding it to the object position during the drag. It was working, but the animation was really choppy and not smooth at all.
I'm sure there is a more simple way to get the mouse coordinates relative to the 3D plan, but wasn't able to find a real solution at this point.
Most of the search results on this subject point to gaming oriented languages, or canvas/webgl questions.
Any ideas ?
Thanks

A: Assuming that your mouse position is an absolute screen position, and you want to grab and slide an object around on a 3D plane based directly on the mouse position:
You can represent your 3D target plane as:

*

*a 3D origin point O

*two 3D vectors U and V, representing the direction of the U- and V-axes

Then, a given 3D point corresponding to plane coordinates [u,v] is:
point3d P = O + u*U + v*V

Then, you can combine the operations that map this particular 3D point to the screen; this is usually described with 3D transformation matrices ModelMatrix, ViewMatrix, and ProjectionMatrix, and a viewport transform determined by a 2D screen origin point origin_2d and a 2D scaling vector scale_2d.  To solve the problem in a readily invertible way, promote everything to homogeneous coordinates, by adding a .w-coordinate to each of them.  This extra coordinate acts as a scaling factor -- to get cartesian coordinates back, you need to divide the homogeneous .x and .y values by the .w value:
P_hom = [u, v, 1] * [U.x, U.y, U.z, 0] = [u, v, 1] * TexMatrix
                    [V.x, V.y, V.z, 0]
                    [O.x, O.y, O.z, 1]

P_clip_hom = P_hom * ModelMatrix * ViewMatrix * ProjectionMatrix
           = P_hom * ModelViewProjectionMatrix

screenpos_hom = P_clip_hom * [scale_2d.x     0        0] = P_clip_hom * PortMatrix
                             [   0        scale_2d.y  0]
                             [   0           0        0]
                             [origin_2d.x origin_2d.y 1]

So, screenpos_hom = [u, v, 1] * TexMatrix * ModelViewProjectionMatrix * PortMatrix
                  = [u, v, 1] * TexToScreenMatrix

-> [screenpos.x, screenpos.y] = [screenpos_hom.x, screenpos_hom.y] / screenpos_hom.w

Note that TexToScreenMatrix is a 3x3 matrix; you should be able to invert it:
UV_2d_hom = [screenpos.x, screenpos.y, 1] * (TexToScreenMatrix)^-1

-> [u, v] = [UV_2d_hom.x, UV_2d_hom.y] / UV_2d_hom.w

Finally, you can either use the [u,v] coordinates directly, or you can use them to recreate the 3D point P as described above.


text:
Q: Bevel highlight with no additional markup
Do you see the thin bevel highlight on top? How do you do this in CSS with only one HTML tag? I'm guessing it has something to do with outline. This is what I have so far without the bevel:
Click here

.callToAction {
 border: 1px solid #000;
 -moz-border-radius: 0.4em;
 background: -moz-linear-gradient(
  top,
  #ccc,
  #999
 );
}

A: To create a bevel you must use a combo of the CSS3 radius and shadow attributes. To get the highlight when hovering over a button you must use the pseudo-selector :hover.
The Button Code from http://www.whitedogdesigngroup.com/blog/entry/a_better_button_with_css3/
callToAction {
  -moz-border-radius: 15px;
  -webkit-border-radius: 15px;
  border-radius: 15px;
  text-shadow: 0 -2px #791c13;
  -moz-box-shadow: 0 1px 1px #ddd, 0 -1px 1px #555;
  -webkit-box-shadow: 0 1px 1px #ddd, 0 -1px 1px #555;
  box-shadow: 0 1px 1px #ddd, 0 -1px 1px #555;
}

callToAction:hover {
  margin-bottom: 1px;
  height: 29px;
  position: relative;
  top: 1px;
  color: #eee !important;

  -moz-box-shadow: 0 1px 1px #eee, 0 -2px 1px #555;
  -webkit-box-shadow: 0 1px 1px #eee, 0 -2px 1px #555;
  box-shadow: 0 1px 1px #eee, 0 -2px 1px #555;
}

If you need further explanation...
Explanation of CSS3 borders: http://doctype.tv/borders
Explanation of CSS3 shadows: http://doctype.tv/css3

A: Just found out that you can specify a shadow to be an inset by inspecting the source of http://html5doctor.com/you-can-still-use-div/:
.inset {
 box-shadow: 0 1px 0 rgba(255, 255, 255, 0.3) inset,
             0 0 2px rgba(255, 255, 255, 0.3) inset,
             0 1px 2px rgba(0, 0, 0, 0.29)
}


text:
Q: sqlfunctions.checksum of linq object I'm trying to figure out how to get the sql statement:
select checksum_agg(checksum(*)) from Foo
to work from linq. I can get the checksum of a single column, so long as I know the column name:
SqlFunctions.ChecksumAggregate(Foo.Select(x => x.Id));
But I would like to either be able to checksum the collection or at least checksum the columns individually without knowing the name(s).

A: The query SqlFunctions.ChecksumAggregate takes is the collection of values over which the checksum is computed. Null values are ignored.
For example, SqlFunctions.ChecksumAggregate(Foo.Select(x => x.Id)); will calculate for each row of the table Foo, for all non-Null columns, calculate the checksum over the Id field.
So the checksum will utilize all info of non-Null columns.