text:
Q: How to get the index of the score from the stored array in game in ios using parse table. In my gaming application, I have scored all the scores of friends, facebook id, name in the array. I have compare my score with friends score and get the rank of my score. How can i do that using objective c code??

A: ..
NSArray *allScores = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:12],
                                                        [NSNumber numberWithInt:43],
                                                        [NSNumber numberWithInt:5],nil];

int myScore = 44;
int myPosition = [self myPositionForScore:myScore inAllScores:allScores];
NSLog(@"myPosition: %i", myPosition);
..

- (int)myPositionForScore:(int)myScore inAllScores:(NSArray *)allScores
{
   NSArray *sortedScores = [allScores sortedArrayUsingSelector:@selector(compare:)];

   for (int position = 0; position < [sortedScores count]; position++) {

       if (myScore <= [[sortedScores objectAtIndex:position] intValue]) {
           return position + 1;
       }
   }

   return [sortedScores count] +1;
}


text:
Q: Proof A=C or B=C A,B,C are sets
we know P(A)∪P(B)=P(C)
and we need to prove A=C or B=C
my way:
we know P(A)∪P(B)=P(C) so
P(A)∪P(B)⊆P(C) and P(C)⊆P(A)∪P(B)
P(A)∪P(B)⊆P(C)
we know A⊆A and B⊆B so A∈P(A) and B∈P(B) so A∈P(C) and B∈P(C) so A⊆C and B⊆C
P(C)⊆P(A)∪P(B)
the same way we get:
C⊆A and C⊆B
and then we get A=C and B=C which is different (but still proofs) from what we need to proof.
Am I wrong anywhere?
thx!

A: Most of it looks good to me. However, the statement $C \subseteq A$ and $C \subseteq B$ isn't true. Try working through that section explicitly and you'll see that you actually get $C \subseteq A$ or $C \subseteq B$, giving the desired result $A = C$ or $B = C$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why .ear and .war folder are created for installed application on WebSphere? I am installing a application(.war file) using wsadmin tool and I am using option

-installed.ear.destination, [target folder]

to installed application in target folder.
But after application is installed, final folder structure for my web contents is like

[target folder]/testapp.ear/testapp.war/[my contents]

why this .ear and .war folders are created and how can I install application so that [my contents] are present in [target folder] ??

A: WebSphere Application Server traditional only runs ear files. So when you install a .war file via the admin console or wsadmin it wraps it in an ear file so it can process it at runtime.

A: That is the a part of the architecture of application deployment for IBM WebSphere Application Server.
As a part of application deployment, the application server places application files in a structure which is convenient for running the application.  That means having easy access to all modules, and means having easy access to files in web modules.
In the case of EJB JAR files, there is no additional layering in the file structure: All elements of an EJB JAR file are accessible through the JAR/ZIP API which is provided by Java.  There is a need to unpackage each EJB JAR file of an application, but there is no need to unpackage elements within the EJB JAR files.
In the case of WAR files, there is an additional layering of JAR files within the WEB-INF/lib folder.  Access to those web module library JARs requires placement of the JAR files as exposed files.
Also, certain resources of WAR files are exposed in the file set for easy access from code areas which are not setup to handle JAR files.  Most prominently, JSP files are exposed on disk so that the JSP compiler has easy access to them.
The net result is that the files of a deployed application expand two layers of the application structure: The EAR file itself is expanded, and WAR files within the EAR are expanded.  JAR type files (EJB JARs, application library JARs, application client JARs, and simple utility JARs packaged within the EAR but not in the application library folder) are not expanded.
There is a possibility of building a more sophisticated API for accessing nested archive files (JAR files within JAR files, or, more or less the same, ZIP files within ZIP files), which treats the nested contents of an application as an extension of the file system.  There are two problems with this sort of strategy.  Either, nested archives must be expanded to temporary locations on demand, or, nested archives must be stored in non-compressed format in the nesting archives.  These two steps are necessary because the ZIP file format does not support seeks on archives which are stored within other archives, where the archives are allowed to use compression on the nested archive.  Because two levels of compression are performed, a seek is possible on the nested archive without removing the level compression on the nested archive.
Tooling can be set to prevent compression when storing a nested archive, but this is not typically done.  And, archives usually have enough regularity that the default ZIP storage algorithm automatically uses compression when storing nested archives.  The most common case is for nested archives to be provided for deployment having two levels compression.

A: The following does suggest itself:
Rename the target application to the target folder name.
Set the target folder name to the parent of the target folder.

For example:
Original target folder: /appsDir/appContent
Original application name: testapp.ear

Modified target folder: /appsDir
Modified application name: appContent.ear

That will get you closer, although, there is still the issue of the file extension on the application archive.
Thomas Bitonti


text:
Q: How to register Android Broadcast Reciever in my QT application? I want to register broadcastReceiver in my application. I am writing a program to print some string when wifi is closed or wifi network is shifted to another network.
Manifest:
<receiver android:name="org.qtproject.example.WifiReceiver" >
   <intent-filter android:priority="100">
      <action android:name="android.net.wifi.STATE_CHANGE" />
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

Java class:
public class WifiReceiver extends BroadcastReceiver
{

String ssid;

@Override
  public void onReceive(Context context, Intent intent) {

       NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
     if(info != null && info.isConnected()) {

       System.out.println("ashoish");

       WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       //ssid = wifiInfo.getSSID();

       ssid="ashish";//SOME STRING
       getinfo(ssid);

     }
}
public native  static String getinfo(String ssid);

}

header file:
JNIEXPORT void JNICALL Java_org_qtproject_example_WifiReceiver_getinfo(JNIEnv * /*env*/,
                                          jobject /*this_obj*/, jstring ssid)
{

    qDebug()<<"ssid is"<<ssid;

}

My expectation is when I close my wifi manually or shift to another wifi manually at least I would get some result due to this line System.out.println("ashoish"); But when I am trying to do so, ashoish is not getting printed which shows onRecieve() is not executed.
Is their any problem in registering BroadcastReciever in manifest file?
How can I solve this?

A: This problem is solved by programmatically registering BroadcastReciever..


text:
Q: Mounting folder as a drive in vista Hi I am trying to mount as a drive in vista I am using the following code from msdn example,
     BOOL bFlag;
   TCHAR Buf[BUFSIZE];     // temporary buffer for volume name

   if( argc != 3 )
   {
      _tprintf( TEXT("Usage: %s <mount_point> <volume>\n"), argv[0] );
      _tprintf( TEXT("For example, \"%s c:\\mnt\\fdrive\\ f:\\\"\n"), argv[0]);
      return( -1 );
   }

  // We should do some error checking on the inputs. Make sure
  // there are colons and backslashes in the right places, etc.

   bFlag = GetVolumeNameForVolumeMountPoint(
              argv[2], // input volume mount point or directory
                  Buf, // output volume name buffer
              BUFSIZE  // size of volume name buffer
           );

   if (bFlag != TRUE)
   {
      _tprintf( TEXT("Retrieving volume name for %s failed.\n"), argv[2] );
      return (-2);
   }

   _tprintf( TEXT("Volume name of %s is %s\n"), argv[2], Buf );
   bFlag = SetVolumeMountPoint(
              argv[1], // mount point
                  Buf  // volume to be mounted
           );

   if (!bFlag)
     _tprintf (TEXT("Attempt to mount %s at %s failed.\n"), argv[2], argv[1]);

   return (bFlag);

It always gives an error of parameter is incorrect , I also tried definedosdevice at first then get the name, It also didn't work. Any idea how to make it work?

A: You need to be more specific! Where exactly in the code do you get that error?
You could try and execute the following command via system() and see if it works this way:
subst K: "c:\blabla"

A: SetVolumeMountPoint is for mounting a volume on a drive letter or in a folder. It does not allow you to mount a folder on a drive letter. This is the opposite of what you want.
To make a folder available as a drive letter, you want to do the equivalent of the SUBST utility. This uses DefineDosDevice, something like this:
if (!DefineDosDevice(0, _T("Q:"), _T("C:\\Temp")))
    _ftprintf(stderr, _T("DefineDosDevice failed: %d\n"), GetLastError());

If you want to make this persistent, I think that you'll need to write a Windows service that does it at boot time. I wrote one about 10 years ago.

A: Instead of trying to make DefineDosDevice persistent, what you'll probably end up doing is resorting to regedit.
REGEDIT4
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices]
"T:"="\\??\\C:\\Temp"

https://en.wikipedia.org/wiki/SUBST#Persisting_across_reboots


text:
Q: Forcing reference type We have the following common pitfall with our codebase.
class FrameworkApplication : public QApplication
{
protected:
    FrameworkApplication(int& argc, char** argv) : QApplication(argc, argv) {}
}

This is an abstract class. Each module that fits within the framework must have its own application class that derives from this base class.
It is imperative that any class that derives from it must pass argc as an int reference.
class MyApplication : public FrameworkApplication
{
public:
    // wrong! argc is not a reference type
    MyApplication(int argc, char** argv) : FrameworkApplication(argc, argv) {}
}

The above mistake is easily made, but it leads to a subtle bug further down the line. One that even the experienced members sometimes fall into and then scratch their head trying to remember the root cause.
And it is very easy to make the above mistake. The compiler does not flag errors or even a warning.
Is there a trick/idiom that we can apply here that forces a compiler error or warning?
Edit
I obviously have tried overloading the ctor of base class FrameworkApplication...
class FrameworkApplication : public QApplication
{
protected:
    explicit FrameworkApplication(int& argc, char** argv);

private:
    explicit FrameworkApplication(int argc, char** argv);
}

But that is considered ambiguous and causes a compiler error on the ctor of class FrameworkApplication.

A: This is an XY problem. There's no reason for argc to be a reference. The real requirement is that argc is an lvalue which remains valid for the lifetime of the QApplication.
The almost-solution is to make argc a member of FrameworkApplication. This doesn't work, though, because FrameworkApplication::argc will be initialized after the QApplication sub-object.
However, the application object is a special case, and so are command lines. There's exactly one per running instance of your program, so you can safely make FrameworkApplication::argc a static member. This fixes the lifetime.
You'll want to pass (FrameworkApplication::argc=argc) as the first argument to QApplication. This makes sure FrameworkApplication::argc is initialized before QApplication uses it.

A: You need to improve your class design, if this problem keeps happening over and over - even for seniors devs who know what is required - then the design is at flaw.
Since an lvalue T will generally convert to a T& without any compilation diagnostics, you cannot get the required effect with just an int& as any lvalue will satisfy that. What you can do instead is use a type which models the behavior you are looking for.
std::reference_wrapper<int> can easily fulfill that purpose. Otherwise, you can roll your own wrapper along similar lines.
P.S.: An even better option would be to avoid the reference entirely and go with a pointer. That has the added advantage of being explicit, which your current design lacks.


text:
Q: Evaluating $\sum_{n=0}^{\infty}{\sin^{3}\left(3^{n}\right) \over 3^{n}}$
How do I find the sum of this series?
  $$\sum_{n=0}^{\infty}{\sin^{3}\left(3^{n}\right) \over 3^{n}}$$

Hints in the right direction would be appreciated.

A: From the identity $ \displaystyle \left(\sin(x)\right)^3 = \left(\frac{e^{ix}-e^{-ix}}{2i}\right)^3$  you get $ \displaystyle \left(\sin(x)\right)^3 = \frac{3}{4}\sin(x)-\frac{1}{4}\sin(3x) $
In particular : $ \displaystyle \frac{\sin^3(3^n)}{3^n} = \frac{3}{4}\left(\frac{\sin(3^n)}{3^n}-\frac{\sin(3^{n+1})}{3^{n+1}}\right)$
So we have a telescopic partial sum : $$ \sum_{n=0}^N \frac{\sin^3(3^n)}{3^n} = \frac{3}{4} \sin(1)-\frac{3}{4} \frac{\sin(3^{N+1})}{3^{N+1}}  $$
So since $ \displaystyle \lim_{x \rightarrow +\infty} \frac{\sin(x)}{x} = 0 $  by taking the limit as $ N  \rightarrow +\infty $ gives : $$ \sum_{n=0}^{+\infty} \frac{\sin^3(3^n)}{3^n} = \frac{3}{4} \sin(1) $$

A: Hint: Use this
$\sin^3x=\frac{3}{4}\sin x - \frac{1}{4}\sin3x. $
Solution:
Let $a_n=\frac{\sin^33^n}{3^n}$ and $b_n=\frac{\sin3^n}{3^n}$. So from the identity mentioned above, one simply has that
$
a_n = \frac{1}{4}(3b_n -3b_{n+1}).
$
Therefore,
$$
\sum_{n\ge 0} \frac{\sin^33^n}{3^n} = \sum_{n\ge 0} a_n = \sum_{n\ge 0} \frac{1}{4}(3b_n -3b_{n+1}) = \frac{3}{4}b_0 =  \frac{3\sin 1}{4}.
$$


text:
Q: Can I install Mint to another hard drive without booting from it? Is there an easy way, given an ISO image for Linux Mint, to install it to an empty hard drive from within my existing Ubuntu installation? I don't have any CDs or appropriate USB devices at hand, so I'm looking for a convenient way to install it without going out and buying some.

A: It is possible to use GRUB2 to boot from an iso file, although it is elaborate. I myself haven't tried it yet apart from my experiences with wubi (and that is a different beast), but here are two links that should help you get started:
http://michael-prokop.at/blog/2009/05/25/boot-an-iso-via-grub2/
http://forums.linuxmint.com/viewtopic.php?f=46&t=66987&start=0

A: You could accomplish this by setting up a virtual machine (using something like VirtualBox). Set the boot media to the iso file and it will easily boot it up. Also configure the VM to have direct access to your empty hard drive, and use that as the primary drive. You should be able to run the install from inside virtualbox, then shut down, switch to that drive as your primary, and be good to go.
Just be careful you attach the right drive to the VM so you don't wipe your system!
As an alternative to vorbote's mention of using grub to boot to the installer iso file, you could also setup a temporary ~1GB partition and use the tools that create a live-usb disk to copy the iso's files there and mark it as bootable. Then you boot up to that partition as if it was a usb disk, and run your install from there.
Lastly, and the way I would do this with my distro is using a simple boot-strap. Package managers can often be given a batch configuration file and a target to build a new system on. You don't mention what your current system is and I don't know how Mint would handle this.


text:
Q: intelligent thin start with port alias for bash i would like a single alias (ts) which starts my local development server. the script should test for an open port starting at 3000 and use the first available port. additionally, some sites require a rackup file, making -R config.ru necessary. this script should check the current directory for the config.ru file and add that to the alias if present.
currently, to start my local development environment, i run:
alias  ts="thin -R config.ru -p 3000 start"

often, i need to run several servers to test different sites, so i've created additional aliases:
alias  ts1="thin -R config.ru -p 3001 start"

A: Well, you could do something clever and look at what ports are already bound using netstat and a command like
netstat -anp | grep LISTEN | awk '{print $4}' | sed s/".*:"//g | sort -n -u

but if you don't care about the ugly console spam you can just keep trying ports until you get one like this
for ((port=3000; port <= 3010 ; port++)); do
   if thin -p $port start; then break; fi
done


text:
Q: Background image, Columns, Scrolls, Tofu, Stanza Is there a way to put a background image (say, a scroll) and have the text imposed on the image?
This means,
columnar text
and some kind of different page definition (image remains the same with the scroll's handles visible)
Idea is to replicate a scroll's functionality along the lines of the discontinued Stanza or Tofu.


text:
Q: GSAP: How to simultaneously tween nested attributes I have a Camera class that has two attributes that I want to animate simultaneously. I want to animate both its distance attribute, which is a number, and the rotation attribute, which has x, y, z elements. I've attempted the following:
Attempt 1:
TweenLite.to(this.camera, 1.0, {distance: 30, rotation.y: 10, rotation.x: 50});

Attempt 2:
TweenLite.to(this.camera, 1.0, {distance: 30, rotation:{y: 10, x: 50}});

Attempt 1 fails because it doesn't allow dot-notation inside the vars parameter. Attempt 2 fails silently and I get no animation whatsoever (in TweenLite v: 1.20.2). Is there a syntax I could use to trigger both distance and rotation animations simultaneously? The only method that has worked gets verbose very quickly once I have more than a few attributes to animate:
TweenLite.to(this.cam, 1.0, {distance: 30});
TweenLite.to(this.cam.rotation, 1.0, {y:10, x: 50});
TweenLite.to(this.cam.position, 1.0, {x:0.5, z: 3});

A: I think you need to use the AttrPlugin
TweenLite.to(this.camera, 1, {attr:{distance: 30, rotation:{y: 10, x: 50}}});


text:
Q: How to draw $U$ such that $ \frac{\partial G}{\partial x} = 0$ and $\frac{\partial G}{\partial y} = 0$ for $(x,y) \in U$? There is a function $G = xy - \frac{x^a}{a} - \frac{y^b}{b}$, $x,y \geq 0 $ and $a > 1$, $b > 1$, $ a - 1 = \frac{1}{b-1}$. I need to draw a set $U = \{ (x,y) | \frac{\partial G}{\partial x} = 0 $ and $\frac{\partial G}{\partial y} = 0 \}$ and calculate value of $G$ at that points of $U$. Since these are partial derivatives I could calculate, say, $\frac{\partial G}{\partial x}$ considering $y$ as a constant, find a first set A which consists of such $x$, then I would do the same for $y$ and it would be set $B$. Does it mean that $U$ is a cartesian product of sets $A$ and $B$? Or another approach can be used here?

A: The set $U$ is not a cartesian product. Being the solution set of the two equations
$${\partial G\over\partial x}=y-x^{a-1}=0,\qquad {\partial G\over\partial y}=x-y^{b-1}=0\tag{1}$$
one would expect that $U$ is the set of intersection points of two curves, hence a hopefully finite set of isolated points. Due to special circumstances this is not the case here: Since $a-1={1\over b-1}$ both equations $(1)$ describe the same curve. Therefore
$$U=\bigl\{(x,y)\bigm| x\geq0, \ y=x^{a-1}\bigr\}\ .$$
Concerning the value of $G$ on the points of $U$ this value is constant: If $t\mapsto \bigl(x(t),y(t)\bigr)$ is a parametrization of $U$ we have to look at
$\phi(t):=G\bigl(x(t),y(t)\bigr)$, and the chain rule tells us that $$\phi'(t)={\partial G\over\partial x}x'(t)+{\partial G\over\partial y}y'(t)\equiv0\ .$$
It follows that
$$G(x,y)=G(1,1)=1-{1\over a}-{1\over b}\qquad\bigl((x,y)\in U\bigr)\ .$$


text:
Q: Xcode copy from mac to laptop shows error I'm primarily developing on my MAC, sometimes I take my project files on a USB-Stick on the go with my macbook, so I can work on things while not at home.
It worked fine so far until now, I'm getting a bunch of Semantic errors, saying that:
"editSetting.settingAnimateSelection = @NO;"

Error: "Property 'editSetting.settingAnimateSelection' not found on object of type 'Setting *'
settingAnimateSelection as well as 2 other items I added to my CoreData structure, I generated the NSManagedSubclass on my mac when I added them, they are declared/defined in the
setting.h
@property (nonatomic, retain) NSNumber * settingAnimateSelection;

also in the
setting.m
@dynamic settingAnimateSelection;

along with a whole bunch of other attributes, there are no relationships.
Everything works on my iMAC, but as soon as I copy my project folder onto my MacBook,
it won't run anymore and shows all those Semantic Errors telling me it can't find them.
I did CLEAN already and tried deleting my app from the simulator and my phone, but nothing helps.
Any ideas? Thanks guys!

A: Solution: You may have multiple instances of like-named files in your source tree. Search for those and delete duplicates from the Xcode project (and possibly tree as well).
Reason: There is a pitfall when re-generating your NSManagedSubclass files...
It is likely (common) that the new generated files (like setting.h and co.) do not go in the very same directory as the old ones. These can easily end up in a nested directory, or have been moved to a different location by the user.
If so, you have multiple versions of source files with the same name in your source tree.
Oddly enough, the one given source file you readily open with the UI is not necessarily the one that the compiler finds.
How to avoid the NSManagedSubclass pitfall:
Xcode > Editor > Create NSManagedObject Subclass... > Select the data models with entities you would like to manage > navigate to the dest directory (you should see your old files) > [Create]
You should get the warning: The following files already exist and will be replaced:...
Additional Notes:

*

*Make sure you are selecting the correct Target>Device>OS. If often resets upon opening on a new Xcode.

*+1 for the repository suggestion. You can use git or svn locally. It would have little or no effect on the problem at hand, though.

A: The best solution is to use a hosted version control system. Then do checkouts, commits and merges.
By default new projects get a local repository, local to the project. Your other options are to stop using local repositories or to save a Snapshot, export the Snapshot from the Organizer and then share that snapshot to your other machine.
By far, hosted repositories are the least trouble in the long run.


text:
Q: Android app with backblaze I am creating an android app which is consuming REST api that were created in Google App Engine(Java).
I also want to store some images and videos which would be uploaded by users when they will use my app.
I was looking for best place to store that data and after some surfing i came across Backblaze, but am not able to find any tutorials, is backblaze used only to backup data or can it work with codes also?

A: It would appear there is an (unofficial?) Java library that you can use with Backblaze.
It does say it requires Java 8, which Android doesn't do, so you'll need to download it as a Maven project and build using Java 6 or 7 with mvn package and add it as a dependency to your project. You'll probably need to fix some Java 8 specific things also, if they are used in that code.
Example code from the README
B2Session session = B2API.authorizeAccount("accountID", "applicationKey");

//Create the Bucket
B2Bucket bucket = B2API.createBucket(session, "ExampleBucket", BucketType.ALL_PRIVATE);

//Retrieve an upload URL
B2UploadRequest request = B2API.getUploadURL(session, bucket);

//Upload the file
B2File file = B2API.uploadFile(request, new File("test.txt"), "test.txt");

A: There is now an official Java SDK for the Backblaze B2 storage API called b2-sdk-java.

A: You can use my library that i'm developing now.. AndroidBackBlazeHelper
//TODO replace applicationKey with your key
//TODO replace applicationKeyId with your key
BlazeClient client = new BlazeClient(this,applicationKeyId,applicationKey);

BlazeFileUploader blazeFileUploader =
new BlazeFileUploader(  client , bucketId); //TODO replace bucketId with your Bucket Id
blazeFileUploader.startUploading(fileUri, fileName , contentType); // replace the content type with mime type or choose one from FileTypes.class e.g. FileTypes.IMAGE_TYPE


text:
Q: (Python) numpy genfromtxt convert problem i use
netdata = num.genfromtxt('resultscut.rw', dtype=None, delimiter = '|', usecols=(0,1,2,3,4))

to generate a list out of a text data file. This works really nice but when i put a bigger data file to convert i get this error:
  File "/home/.local/lib/python2.7/site-packages/numpy/lib/npyio.py", line 2047, in genfromtxt
    for (i, conv) in enumerate(converters)]))
MemoryError

Is it too big for genfromtxt? How can i fix it?
Thank you in advance,
Greetings :)

A: As discussed in the comments, the resulting object is probably too large for your memory.
Numpy has the ability to store arrays on your disk (hopefully SSD, if you use a HDD, this will probably be too slow).
This is called a memmap.
It is possible to store datatypes such as strings in a memmap, but this can become tricky: numpy.memmap for an array of strings?
Also, it might be complicated to get the data into the memmap in the first place. You might want to split the file and load it in multiple goes. Then you can write the individual portions into the memmap one by one.
Another important point might be the dtype. You specify None and use many columns. Are you having different datatypes in the different columns ? If yes, you might want to switch to pandas, instead of numpy. That will give you a proper datatype for this spreadsheet like data.
Be sure to use the appropriate datatypes for every column. That can significantly reduce your memory footprint (and might already solve your problem): https://www.dataquest.io/blog/pandas-big-data/
To check the memory footprint of a numpy array, you can use nbytes:
np.ones((10,10), dtype="float64").nbytes # 800
np.ones((10,10), dtype="int32").nbytes # 400


text:
Q: How can i remove all characters started with # from a textarea using jquery or javascript? I have the code below
<textarea id="description" name="description" rows="10" placeholder="Description..." class="valid">
This is an example text i wanna keep.
# And i want to remove all this content.
</textarea>

how can i remove only this text from the textarea
# And i want to remove all this content.

using jquery or javascript ?
As you can see i want all the content that start with a hashtag to be removed.

A: Only for textarea, you may use a simple Regular Expression, with "m" (multiline) flag.
• Where $ means end of the line;
• special . matches with any symbol,
• * means 'match from zero to infinite times'

let desc = document.getElementById('description');

desc.value = desc.value.replace(/#.*$/gm,"");
textarea {width: 80%;}
<textarea class="js-replace" id="description" name="description" rows="10" placeholder="Description...">
This is an example text i wanna keep.
# And i want to remove all this content.

Bubu and replace #Me
But not me!
</textarea>

Version for multiple elements, textarea, div, etc - replace by className:

let replace = document.querySelectorAll('.js-replace')

for( let i = 0; i < replace.length; i++ ){
  let area = /TEXTAREA|INPUT/.test(replace[i].tagName); // will return true or false;
  let content = area ? "value" : "innerHTML";
  // Ternary operator. (condition) ? (value if true) : (value otherwise)

  // replace[i]['value'] if textarea and replace[i]['innerHTML'] if other element
  replace[i][content] = replace[i][content].replace(/#.*?(\n|
|$)/g, "$1"); // (*1)
}
textarea {width: 80%;}
<textarea class="js-replace" id="description" name="description" rows="10" placeholder="Description...">
This is an example text i wanna keep.
# And i want to remove all this content.

Bubu and replace #Me
But not me!
</textarea>

  This is an example text i wanna keep.

# And i want to remove all this content.

Bubu and replace #Me

But not me!

(*1): .replace(/#.*?(\n|
)/g, "$1") — string, starting from # symbol, matching .* anything (instead of line-break \n), many times, and ? stop as soon as it faces with \n line break | or
 HTML-line break. "$1" — equals to match in the first (parentheses). I.e. we replace all string, but keep line-break.
But this will not work correctly, if you want to delete, for example, comments from Python... because you may delete strings with "str... # str"


text:
Q: On change even handlers for a datepicker on a dynamically inserted input tag doesn't work? I have two dynamically inserted  tags with IDs pick-from and pick-to. I am using this plugin: http://www.eyecon.ro/bootstrap-datepicker/ to call a datepicker when it is clicked and perform some tasks when the date changes. It used to work when the input tags were not dynamically inserted but the application behavior had to be changed and now, the input tags are dynamically inserted. The code below no longer works:
var picker = $('#pick-from, #pick-to').datepicker().on('changeDate', function(ev) {
        picker.datepicker('hide');

        var today   = new Date(ev.date),
            dd      = today.getDate(),
            mm      = today.getMonth() + 1,
            yyyy    = today.getFullYear();

        if (dd < 10) dd = '0' + dd;
        if (mm < 10) mm = '0' + mm;

        var inputVal    = mm + '/' + dd + '/' + yyyy,
            target      = ev.currentTarget.id;

        // All my other code goes here.
    });

I even tried:
$(document).on('click', '#pick-from, #pick-to', function() {
    var picker = $(this).datepicker().on('changeDate', function(ev) {
        picker.datepicker('hide');

        var today   = new Date(ev.date),
            dd      = today.getDate(),
            mm      = today.getMonth() + 1,
            yyyy    = today.getFullYear();

        if (dd < 10) dd = '0' + dd;
        if (mm < 10) mm = '0' + mm;

        var inputVal    = mm + '/' + dd + '/' + yyyy,
            target      = ev.currentTarget.id;

        // A lot of other code comes here.
    }});

The second code snippet works but not consistently. It works when I click on both input boxes and click on either one for the second time. How do I fix this?

A: You can apply the event to the container element and delegate it:
$("#myContainer").on('changeDate', '#pick-from, #pick-to', function() { ... });

http://api.jquery.com/on/
.on( events [, selector ] [, data ], handler )

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.


text:
Q: How to provide hints to IntelliJ to exclude properties when using generate With IntelliJ 2016.2 is there a way to mark a property/method that should not be included when generation of code is done?
For example this class
public class Person {
    private String firstName;
    private String lastName;

    public void setFirstName(String firstName){ ... }
    public String getFirstName() { ... };

    public void setLastName(String firstName){ ... }
    public String getLastName() { ... };

    public String getFullName() { // returns first + last };
}

I would like to mark getFullName so it is not used when generating things like equals or toString since it is merely a connivence function.

A: This isn't a full answer, but when you generate equals/hashcode, the first screen has an option to select a template. Choose "..." and you can create your own new template for creating equals and hashcode. You might therefore be able to code something, eg reading an annotation on a field, that would allow you to exclude it from the generation.
These look suspiciously like Velocity macros to me but my understanding of them isn't good enough to take the solution any further.


text:
Q: Exception Catching Best Practices on 3 Tier Application I've a WCF with following 3 tiers:

*

*Service

*BLL

*DLL.

Could anyone please help me out on:
Which one of the above tier is the best place to catch and log the exception on following scenario:

Scenario 1:
Exception happens on DLL.
Scenario: 2:
Exception happens on BLL.

Also, should I always always wrap the call to BLL from Service on Try and Catch?

A: it depends on your system here, but I would log the exceptions probably inside the BLL. And mind you "log" not catch! That is - at the end of the catch will stand a rethrow!
I don't catch anything in the service at all - this is just to communicate with the client - no need to put any logic inside it IMHO.
And of course: catch your expected exceptions where they are thrown and just let the unexcepted pass.
For example:
Scenario 1 - maybe catch SqlExceptions, try handle them and if not wrap them in some DAL-Exception and throw these.
Scenario 2 - maybe catch the DAL-Exceptions from Layer 3 and see if you can handle those or wrap them yet again, ...
IMHO it's almost never a good idea to handle, log and mute all kinds of unexcpected exceptions (catch (Exception)) - the app state will just be very undefined after this.

A: Have a read through some of the articles on MSDN about the Microsoft Exception Handling Block
It goes through a lot of scenarios and give you some good ideas for exception handling strategy best practices regardless of whether you use the exception handling block or not, as shown in the diagram below.


text:
Q: want to update JSON using N1QL I want to update couchbase json. look at first JSON
{
  "_id": 4,
  "_type": "Company",
  "balance": "0",
  "companyTypes": [
    1,
    2
  ],
  "transactions":{
      "amount": "120",
      "method": 2,
      "transactionType": "4"
    }
}

I want to update

*

*companyTypes as 1,3

*transactions-> method=3

How can I do this using N1QL ??

A: This will address your specific question. You can generalize the pattern.
Note that this is all documented in the link from @cricket_007.
UPDATE mybucket
SET companyTypes = [1, 3],
    transactions.method = 3
WHERE ...;


text:
Q: How to do UDP multi chat server socket program using threading? I am completely new to network and socket programming. I have tried some code; say I have 3 clients and a server c1 messages and it goes through server and reflected in c2 and c3.
My problem:

*

*I don't want to see my own message (if I say "hi" it's showing for me also but it should be shown in c2 and c3 only).

*is there a way like only c2 can see a message and not c3 when c1 sends it

*unable to do this in Python and error is shown, so how can be it done in Python 3

server.py
import socket
import time

host = ''
port = 5020

clients = []

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
a=s.bind((host, port))
#s.setblocking(0)

quitting = False
print "Server Started."
print("socket binded to %s" % (port))
while not quitting:
    try:
        data, addr = s.recvfrom(1024)
        if "Quit" in str(data):
            quitting = True
        if addr not in clients:
            clients.append(addr)
            #print clients
        for client in clients:
            if not a:# tried this for broadcasting to others not c1

                s.sendto(data, client)

        print time.ctime(time.time()) + str(addr) + ": :" + str(data)

    except:
        pass
s.close()

This is Python 2 code.
client.py
enter code hereimport socket
import threading
import time

shutdown = False

def receving(name, sock):
    while not shutdown:
        try:

            while True:
                data, addr = sock.recvfrom(1024)

                print str(data)
        except:
            pass

host = ''
port = 5020

server = ('',5020)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
#s.setblocking(0)

for i in range(5):
    threading.Thread(target=receving, args=("RecvThread",s)).start()

alias = raw_input("Name: ")
message = raw_input(alias + "-> ")
while message != 'q':
    if message != '':
        s.sendto(alias + ": " + message, server)

    message = raw_input(alias + "-> ")

    time.sleep(0.1)

shutdown = True

s.close()

The output am getting in server is correct the time and server message, but my problem is client output c1 message is shown in c1 itself.
 Name: c1
 c1-> hi
 c1-> c1: hi

see the 3rd line the message "hi" is shown to me also.

A: Instead of
for client in clients:
   if not a:# tried this for broadcasting to others not c1

      s.sendto(data, client)

You can do this:
for client in clients:
   if client!=addr:# tried this for broadcasting to others not c1

       s.sendto(data, client)

Because address of every connected client is stored in addr variable when you do this:
data, addr = s.recvfrom(1024)


text:
Q: Netcat Chat bash script problems I'm creating a sh script for a Chat using netcat.
This is the code:
#!/bin/bash

clear

echo
echo "-----------------------"
echo "| handShaker Chat 2.0 |"
echo "-----------------------"
echo

read -p 'Server or Client setUp? (s or c) > ' type

if [ $type == 's' ] || [ $type == 'S' ] || [ $type == 'server' ]
then
    read -p 'Port (4321 Default) > ' port
    if [ $port -gt 2000 ] && [ $port -lt 6500 ]
    then
        echo
        echo "Started listening on port $port."
        echo "Stream (Press ctrl + shift to end session) >"
        echo
        awk -W interactive '$0="Anonymous: "$0' | nc -l $port > /dev/null
    else
        echo "handShaker Error > The port $port is not a in the valid range (2000 ... 6500)."
    fi
elif [ $type == 'c' ] || [ $type == 'C' ] || [ $type == 'client' ]
then
    read -p 'Port (4321 Default) > ' port
    if [ $port -gt 2000 ] && [ $port -lt 6500 ]
    then
        read -p 'Destination IP > ' ip
        if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
        then
            echo
            echo "Started streaming $ip on port $port."
            echo "Stream (Press ctrl + shift to end session) >"
            echo
            awk -W interactive '$0="Anonymous: "$0' | nc $ip $port > /dev/null
        else
            echo "handShaker Error > Invalid IP Address."
        fi
    else
        echo "handShaker Error > The port $port is not a in the valid range (2000 ... 6500)."
    fi
else
    echo "handShaker Error > $type is not a valid keyword."
fi

But I have the following problems: the awk -W parameter doesn't seem to exist, and the program actually stops after running the client.
I'm using the macOS terminal.
Can someone help me to fix this bugs and to improve my script?

A: Your script has an incorrect & unnecessary usage of awk with -W interactive flags which are not defined in any of the flavours of awk. Removing it should solve your problem.
Also your script has a bunch of bash variables defined and used without double-quoting. Remember to double quote variables prevent globbing and word splitting.


text:
Q: Entity has no architecture problem in Modelsim I'm new to FPGA design using VHDL and I'm stucked in a problem of testbench simulation: each time I try to simulate my model (which testbench was given by the testbench writer) I get the following error that's driving me crazy:

Error: (vsim-3173) Entity >'C:/intelFPGA_lite/progetto_dsp/simulation/modelsim/rtl_work.progetto_dsp_top_vhd_t>st' has no architecture.

My model is a simple Phase Frequency Detector (PFD) and all I'd like is to simulate its behavior at different input signals.
Following I post my testbench code, the only thing that I changed from the auto-generated code is the addition of the A and B signals (which I made like clock signals with different frequency).
-- Generated on "05/02/2021 16:58:30"

-- Vhdl Test Bench template for design  :  progetto_dsp_top
--
-- Simulation tool : ModelSim-Altera (VHDL)
--

LIBRARY ieee;
USE ieee.std_logic_1164.all;

ENTITY progetto_dsp_top_vhd_tst IS
END progetto_dsp_top_vhd_tst;
ARCHITECTURE progetto_dsp_top_arch OF progetto_dsp_top_vhd_tst IS
-- constants
constant period_A : time := 10 ps;
constant period_B : time := 20 ps;
-- signals
SIGNAL A : STD_LOGIC := '0';
SIGNAL B : STD_LOGIC := '0';
SIGNAL High : STD_LOGIC : '1';
SIGNAL QA : STD_LOGIC;
SIGNAL QB : STD_LOGIC;
COMPONENT progetto_dsp_top
    PORT (
    A : IN STD_LOGIC;
    B : IN STD_LOGIC;
    High : IN STD_LOGIC;
    QA : OUT STD_LOGIC;
    QB : OUT STD_LOGIC
    );
END COMPONENT;
BEGIN
--signal A generation
process
    begin
        A <= '1';
        wait for period_A/2;
        A <= '0';
        wait for period_A/2;
        if end_sim_s = true then
            wait;                       -- end of simulation
        end if;
    end process;

signal B generation
process
    begin
        B <= '1';
        wait for period_B/2;
        B <= '0';
        wait for period_B/2;
        if end_sim_s = true then
            wait;                       -- end of simulation
        end if;
    end process;
    i1 : progetto_dsp_top
    PORT MAP (
-- list connections between master ports and signals
    A => A,
    B => B,
    High => High,
    QA => QA,
    QB => QB
    );
init : PROCESS
-- variable declarations
BEGIN
        -- code that executes only once
WAIT;
END PROCESS init;
always : PROCESS
-- optional sensitivity list
-- (        )
-- variable declarations
BEGIN
        -- code executes for every event on sensitivity list
WAIT;
END PROCESS always;
END progetto_dsp_top_arch;


text:
Q: Do elements of a list inside a dictionary change it's order in Python? I have a list inside a dictionary, it seems to change it's order in every iteration.
Consider this example,
a={ID: [value, [1,2,3,4,5,6]]}

When I access a[ID][1], will it give [1,2,3,4,5,6] (in order) everytime I access this?

A: Yes, a[ID][1] should give the same list in order each time.  Unless you change a somewhere else within your program.


text:
Q: Removing double quotes from json response I use basic array to make reference to icons like this:
{name: "text", avatar: srcs[15]}

This works great, but now I dynamically create an array from my json api and it gives me array of objects like this:
{name: "text", avatar: "srcs[15]"}

so I cannot reference to my avatars now. How can I remove double quotes to get my array work again?
Please note that I don't want to get the srcs[15] value to the array, just make a reference to the source array.

A: The JSON data format does not support references. What you want it not possible.
You need to either:

*

*Put the data you want there explicitly (this may involve duplication) or

*Describe the relationship in a way that the program consuming the JSON can interpret as a reference. You could use the reviver argument of JSON.parse to inflate the description back to the data you want to point it to.

A: JSON is self-contained static data, and it can't reference named variables or objects outside of its own structure.
You can do it like this instead:
{ "name": "text", "avatarIndex": 15 }

And then do one of these to use it:
var avatar = srcs[data.avatarIndex];  // Avatar object in separate variable
// or
data.avatar = srcs[data.avatarIndex]; // Avatar object added into data

A: You should just put either the value or the whole array , you have also to read about what format json support here
Here's my suggested solutions

var array = [1, 2, 3, 4, 5, 6]

var json1 = {
  name: 'test',
  value: array
}

console.log("solution 1 :" + json1.value[2])

var json2 = {
  name: 'test',
  value: array[2]
}

console.log("solution 2 :" + json2.value)


text:
Q: Scanning manifest classpath jars in Embeeded Tomcat I have an embedded Tomcat application packaged as an executable (thin) jar with multiple external jar dependencies.
The build process generates a META-INF/MANIFEST.MF with header fields Main-Class and Class-Path (with an entry per runtime dependency).
I want to execute the application using a simple java -jar my_app.jar, but I am unable to make Tomcat scan these dependent jars (in order to discover TLDs or @HandlesTypes classes like Spring WebApplicationInitializer).
I am configuring the jar scanning this way:
StandardJarScanner jarScanner = (StandardJarScanner) ctx.getJarScanner();
jarScanner.setScanBootstrapClassPath(true);
jarScanner.setScanClassPath(true);

And all the jars has a META-INF folder, but the scanner completely ignores them.
Any ideas?

Note: I can make this work using different approaches (fat jar, running from maven, ...) but I am interested in making it work this way, as any other java application.

A: Tomcat gets the jar URLs to scan by repeatedly calling URLClassLoader.getURLS() in the class loader hierarchy (bottom up)
The problem arises for the system class loader since URLClassLoader.getURLS() does not return the classpath jars when the java application is executed as java -jar <executable-jar>
See: How does a classloader load classes reference in the manifest classpath?
In the previous post it is suggested to use reflection to access a private field in the system classloader instance, but this presents several problems:

*

*This accession can be forbidden by a security manager

*The solution is implementation dependent

So I figured out another way:

*

*For a given classloader enumerate all the manifest available cl.getResources("META-INF/MANIFEST.MF"). These manifests can be of jars managed by the current class loader or its ascendants classloaders.

*Do the same for its parent classloader

*Return the set of jars of those manifest in (1) but not in (2)

The only requirement for this method to work is that jars in the classpath must have a manifest in order to be returned (not much to ask).
/**
 * Returns the search path of URLs for loading classes and resources for the
 * specified class loader, including those referenced in the
 * {@code Class-path} header of the manifest of a executable jar, in the
 * case of class loader being the system class loader.
 * <p>
 * Note: These last jars are not returned by
 * {@link java.net.URLClassLoader#getURLs()}.
 * </p>
 * @param cl
 * @return
 */
public static URL[] getURLs(URLClassLoader cl) {
    if (cl.getParent() == null || !(cl.getParent()
            instanceof URLClassLoader)) {
        return cl.getURLs();
    }
    Set<URL> urlSet = new LinkedHashSet();
    URL[] urLs = cl.getURLs();
    URL[] urlsFromManifest = getJarUrlsFromManifests(cl);
    URLClassLoader parentCl = (URLClassLoader) cl.getParent();
    URL[] ancestorUrls = getJarUrlsFromManifests(parentCl);

    for (int i = 0; i < urlsFromManifest.length; i++) {
        urlSet.add(urlsFromManifest[i]);
    }
    for (int i = 0; i < ancestorUrls.length; i++) {
        urlSet.remove(ancestorUrls[i]);
    }
    for (int i = 0; i < urLs.length; i++) {
        urlSet.add(urLs[i]);
    }
    return urlSet.toArray(new URL[urlSet.size()]);
}

/**
 * Returns the URLs of those jar managed by this classloader (or its
 * ascendant classloaders) that have a manifest
 * @param cl
 * @return
 */
private static URL[] getJarUrlsFromManifests(ClassLoader cl) {
    try {
        Set<URL> urlSet = new LinkedHashSet();
        Enumeration<URL> manifestUrls =
                cl.getResources("META-INF/MANIFEST.MF");
        while (manifestUrls.hasMoreElements()) {
            try {
                URL manifestUrl = manifestUrls.nextElement();
                if(manifestUrl.getProtocol().equals("jar")) {
                    urlSet.add(new URL(manifestUrl.getFile().substring(0,
                            manifestUrl.getFile().lastIndexOf("!"))));
                }
            } catch (MalformedURLException ex) {
                throw new AssertionError();
            }
        }
        return urlSet.toArray(new URL[urlSet.size()]);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

Tomcat registered issue: https://bz.apache.org/bugzilla/show_bug.cgi?id=59226


text:
Q: Swing window empty when used from other class I am new to Swing and have a problem starting a window from another class. If i create a new object of the window in the same class it shows up just fine, but as soon as i try to start it from another class it shows up empty.
This is what i tried, but it's not working:
ProgressWindow dow = new ProgressWindow(this, null);

Here the code for my Swing window:
package example;

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ProgressWindow extends javax.swing.JFrame {

    private final JPanel panel;
    private final javax.swing.JLabel jLabel1;
    private final javax.swing.JLabel jLabel2;
    private String message = "Vorgang läuft...";
    private final int maxLength = 30;

    public ProgressWindow(JFrame frame, String pMessage) {
        super("Bitte warten");
        //Set Message
        setMessage(pMessage);
        //Labels und panel anlegen
        panel = new JPanel(new GridLayout(2, 1));
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        //Position
        this.setLocationRelativeTo(frame);
        //Close-Operation
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        //Size
        setMaximumSize(new java.awt.Dimension(240, 90));
        setMinimumSize(new java.awt.Dimension(240, 90));
        setResizable(false);
        //Content
        jLabel1.setText(message);
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xyz/ajax-loader.gif")));
        //Alignment
        jLabel1.setHorizontalAlignment(JLabel.CENTER);
        jLabel2.setHorizontalAlignment(JLabel.CENTER);
        //Finish Layout
        panel.add(jLabel1);
        panel.add(jLabel2);
        getContentPane().add(panel);
        pack();
        setVisible(true);
    }

    private void setMessage(String pMessage) {
        if (pMessage != null) {
            //Cut string if too long
            if (pMessage.length() > maxLength) {
                pMessage = pMessage.substring(0, maxLength) + "...";
            }
            this.message = pMessage;
        }
    }

    //This works as expected:
    public static void main(String[] args) {
        try {
            ProgressWindow pr = new ProgressWindow(null, null);
            Thread.sleep(2000);
            pr.dispose();
        }
        catch (InterruptedException ex) {
        }
    }
}

Here a quick and dirty example-class i created with the Netbeans GUI-Builder, to demonstrate the code that does not work:
package example;

public class Otherclass extends javax.swing.JFrame {

    public Otherclass() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(317, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(266, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        try {
            ProgressWindow pr = new ProgressWindow(this, null);
            Thread.sleep(2000);
            pr.dispose();
        } catch (InterruptedException ex) {
            System.err.println(ex);
        }
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Otherclass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Otherclass().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration
}

A: Use Swing Timer instead of Thread.sleep(2000) in a Swing application.
Read more How to Use Swing Timers
Sample code:
final ProgressWindow pr = new ProgressWindow(null, null);
Timer timer=new Timer(2000,new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
       pr.dispose();
    }
});
timer.setRepeats(false);
timer.start();

A: You should use the frame passed to constructor.
Change those calls in your constructor to:
    frame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    //Size
    frame.setMaximumSize(new java.awt.Dimension(240, 90));
    frame.setMinimumSize(new java.awt.Dimension(240, 90));
    frame.setResizable(false);

    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);


text:
Q: How to configure Linux to close the connection if Send-Q is never sent? There is a TCP client-server connection. The application on the server is sending data regularly. Client machine is then reset physically. Netstat shows Send-Q on the server is filling up, the connection is in the ESTABLISHED state. How to make it disconnect?
The packets are being added to the Send-Q, obviously nothing is sent. The connection closes only after about 5 minutes.
I'd like to set a timeout so if there aren't any packets leaving the Send-Q then close that connection. How to do that?


text:
Q: How to extract link from html script in python? How can I extract the URL from a script of HTML with Python?
The HTML provided:

function download() {
                window.open('https:somelink.com');
        }
        const text = `

`;

function embed() {
                var element = document.getElementById('embed-text');
                console.log(element);
                element.innerHTML = text

        }

Desired output will be:
https://somelink.com

Any help will do. Thanks!

A: You should use regex like this:

var urlRegex = /(https?:\/\/[^\s]+)/; // the regex
// your string
var input = "

";

console.log(input.match(urlRegex)[1]); // use regex and lot result


text:
Q: Generating custom ID for my application I want to generate a custom ID for one of the feature in my application. Here is the procedure to do that:
CREATE PROCEDURE [dbo].[GetNextVendorInvoiceNo]
AS
BEGIN

    Declare @StartingVendorInvoiceNo    int = 0

    Select @StartingVendorInvoiceNo = MAX(StartingVendorInvoiceNo) + 1
        From SystemSettings WITH (TABLOCK)

    Update SystemSettings
            Set StartingVendorInvoiceNo = @StartingVendorInvoiceNo

    Select @StartingVendorInvoiceNo

END

Would there be any issue if multiple users end up calling this procedure. Obviously I don't want multiple users to have the same ID. I am using TABLOCK but not sure if this is the right way or anything else too is required.

A: SQL Server 2012 has SEQUENCE feature, which is definitely safe for multi-user environment. It is based on an integer type, though.
If you have a complex procedure that generates a "next" ID and you want to make sure that only one instance of the procedure runs at any moment (at the expense of throughput), I'd use `sp_getapplock'. It is easy to use and understand and you don't need to worry about placing correct query hints.
Your procedure would look like this:
CREATE PROCEDURE [dbo].[GetNextVendorInvoiceNo]
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRANSACTION;
    BEGIN TRY

        DECLARE @VarLockResult int;
        EXEC @VarLockResult = sp_getapplock
            @Resource = 'GetNextVendorInvoiceNo_app_lock',
            @LockMode = 'Exclusive',
            @LockOwner = 'Transaction',
            @LockTimeout = 60000,
            @DbPrincipal = 'public';

        Declare @StartingVendorInvoiceNo int = 0;

        IF @VarLockResult >= 0
        BEGIN
            -- Acquired the lock, generate the "next" ID
            Select @StartingVendorInvoiceNo = MAX(StartingVendorInvoiceNo) + 1
            From SystemSettings;

            Update SystemSettings
            Set StartingVendorInvoiceNo = @StartingVendorInvoiceNo;

        END ELSE BEGIN
            -- TODO: handle the case when it takes too long to acquire the lock,
            -- i.e. return some error code
            -- For example, return 0
            SET @StartingVendorInvoiceNo = 0;
        END;

        Select @StartingVendorInvoiceNo;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        -- TODO: handle the error
    END CATCH;

END

Simple TABLOCK as you wrote is definitely not enough. You need to wrap everything into transaction. Then make sure that lock is held till the end of the transaction, see HOLDLOCK. Then make sure that the lock you are getting is the correct one. You may need TABLOCKX. So, overall you need a pretty good understanding of all these hints and how locking works. It is definitely possible to achieve the same effect with these hints. But, if the logic in the procedure is more complicated than your simplified example it can easily get pretty ugly.
To my mind, sp_getapplock is easy to understand and maintain.


text:
Q: Add not relevant column to group by script This is my sample table and values:
CREATE TABLE [dbo].[Test]
(
[Id]     BIGINT  NOT NULL  DEFAULT(0),
[VId]    BIGINT  NOT NULL  DEFAULT(0),
[Level]  INT     NOT NULL  DEFAULT(0)
);

INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (100, 1, 1);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (101, 1, 2);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (102, 1, 3);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (103, 2, 1);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (104, 3, 1);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (105, 3, 2);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (106, 4, 1);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (107, 4, 2);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (108, 4, 3);
INSERT INTO [dbo].[Test] ([Id], [VId], [Level]) VALUES (109, 4, 4);

So at now I use this script:
SELECT
    [T].[VId], MAX ([T].[Level]) AS [MaxLevel]
FROM
    [dbo].[Test] AS [T]
GROUP BY
    [T].[VId];

And it returns:
VId    MaxLevel
1      3
2      1
3      2
4      4

But I need Id column also and I can't add it to Group by script, I need the following values:
VId    MaxLevel   Id
1      3          102
2      1          103
3      2          105
4      4          109

What is your suggestion?
Also The following values is enough The Id's With Max(Level) in any VId :
Id
102
103
105
109

A: A 2008 take on the question, since that's what you're working with:
declare @Test table
(
[Id]            BIGINT      NOT NULL    DEFAULT(0),
[VId]           BIGINT      NOT NULL    DEFAULT(0),
[Level]         INT         NOT NULL    DEFAULT(0)
);

INSERT INTO @Test ([Id], [VId], [Level])
VALUES (100, 1, 1),(101, 1, 2),(102, 1, 3),(103, 2, 1),(104, 3, 1),
(105, 3, 2),(106, 4, 1),(107, 4, 2),(108, 4, 3),(109, 4, 4);

;With Numbered as (
    select *,
        RANK() OVER (PARTITION BY VId ORDER BY [Level] desc) as rn
from @Test)
select VId,Level,Id from Numbered where rn=1

Note that (as with the other solutions) this will output multiple rows per VId if there are two rows with the same maximum level. If you don't want that, switch RANK() to ROW_NUMBER() and an arbitrary one will win - or if you want a specific winner in the case of a tie, add that condition into the ORDER BY of the window function.

A: Use joining with the same table by VId column
something like this:
SELECT [T].[VId], [T].[MaxLevel], [T1].[Id]
FROM [dbo].[Test] AS [T1] JOIN
  (SELECT [T].[VId], MAX ([T].[Level]) AS [MaxLevel]
    FROM [dbo].[Test] AS [T]
    GROUP BY [T].[VId]) AS [T]
ON [T1].[VId] = [T].[VId]
AND [T1].[Level] = [T].[MaxLevel]
ORDER BY [T].[VId];

the result will be:
VId MaxLevel  Id
1   3         102
2   1         103
3   2         105
4   4         109

A: Use this:
WITH LastLevels AS
(
SELECT
    [T].[VId] AS [VID],
    MAX ([T].[Level]) AS [MaxLevel]

FROM [dbo].[Test] AS [T]
GROUP BY [T].[VId]
)

SELECT [LastLevels].[VID],[LastLevels].[MaxLevel], [Te].[Id]
FROM [dbo].[Test] AS [Te]
INNER JOIN [LastLevels]
ON [LastLevels].[VID]=[Te].[VId]
AND [LastLevels].[MaxLevel]=[Te].[Level]
ORDER BY [LastLevels].[VID];

A: SELECT ID, [VId], [MaxLevel] From
(
    SELECT
        [T].[VId], MAX ([T].[Level]) AS [MaxLevel]
    FROM
        [dbo].[Test] AS [T]
    GROUP BY
        [T].[VId]
)K
INNER JOIN [Test] T on T.[VId] = K.[VId] and T.[Level] = K.MaxLevel


text:
Q: how eliminate orphans when filtering in RDL SSRS I filtered my report based on a certain expression. Those that do not meet the criteria that I put in my IFF expression are then filtered and those that do meet it, are shown in my report. My report is multiple pages, so when the filtering happens, some records are left alone on a page, and are not moved up. This leaves a lot of whitespace, and I would like to get rid of that.
On page 1, there will be 2 images/records, with space for one more
On page 2, there will be only 1 image/record that would fit on page one, but doesn't move up
on page 3, there will be only 1 image/record that would fit on page 2 but stays on page 1 etc...
my Keeptogether value is set to true, however this does not help. I have been trying to find something that will keep these records together when filter happens, so that the number of pages is minimal.
If someone could help, I'd really appreciate it.
Regards
Jay

A: Are you "filtering" via the Visibility in Properties? Because such way will just hide, rather than rule out, the records/images you don't want. If that's the case, try filtering via the Filter in the Properties of the tablix (or Groups, if it applys to your case). But I think the best way is to do the filter job in you data set query, because that will provide you best performance.

A: So i resolved my problem by adding my IFF expression that I orginially had in the visibility option to the filter by expression option. Everything now moves up and the extra white space that was there before is gone.
Thank you for your help!! :)


text:
Q: Return type of this for inherited TypeScript classes not working I'm trying to create a base class where inheriting classes must implement a method that returns objects of the same type as itself.
abstract class Base {
  abstract clone(): this;
}

class Impl extends Base {
  clone(): this {
    return new Impl();
  }
}

Unfortunately, I get this error.

Type 'Impl' is not assignable to type 'this'.
    'Impl' is assignable to the constraint of type 'this', but 'this' could be instantiated with a different subtype of constraint 'Impl'.(2322)

I can work around this with casting magic:
abstract class Base {
  abstract clone(): this;
}

class Impl extends Base {
  clone(): this {
    return new Impl() as this;
  }
}

...but I don't understand why this is necessary. Why is a new Impl() not of type this?

A: Error says that, if you subclass Impl, function clone() of your resulting subtype won't fit defined constraints.
class Impl2 extends Impls {
}

const impl2 = new Impl2();
impl2.clone(); // method would return Impl type, instead of Impl2 type, so `this` is not correct constraint.

As of this moment, while there is a workaround to prevent further inheritance from Impl class by usingprivate contructor(), compiler/language service will still report the error, as there is no way to mark class as sealed/final.


text:
Q: How to upload a MS flow package to another SharePoint site I'm new in MS flow I'm importing a flow package from a SharePoint site and upload into another SharePoint site.

A: If you are trying to migrate flow in same environment/tenant for another SharePoint site, you can create a copy of your flow using "Save as" option and edit it to reference new SharePoint site.

If you are trying to migrate it to another environment/tenant, you can export and import individual flows across environments with packaging.
OR if you have multiple flows, it is recommended to use solutions for flow migrations. You can use solution export and import in this case.
Check below links for more information:

*

*Export a solution and Import a solution

*Export and import your flows across environments with packaging

*Migrate Flows between SharePoint sites and Flow Environments


text:
Q: AWS Gateway proxy to an existing WebSocket server thank you for reading this question.
what is the way to use AWS API Gateway to proxy communication to a WebSocket server running on EC2?
I tried HTTP/REST and WebSocket with no success.
thank you


text:
Q: CMTimeMake crash when making video thumbnail I'm trying to make a video thumbnail, and was following another tutorial here on SO. I'm sure I've done everything it told me to do, but it's still not working...
This is the error I get:
Undefined symbols for architecture armv7:
"_CMTimeMake", referenced from:
  -[MainMenuController imagePickerController:didFinishPickingMediaWithInfo:] in MainMenuController.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The code:
AVURLAsset* asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:movieUrl] options:nil];
    AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    pickedImage = [UIImage imageWithCGImage:[imageGenerator copyCGImageAtTime:CMTimeMake(1, 1) actualTime:nil error:nil]];

Do any of you have any idea of what might be wrong?
I have included the AVFoundation Framework, just fyi...
Thanks in advance, Tom

A: CMTimeMake is defined in the CoreMedia framework, so you probably have to add
#import <CoreMedia/CoreMedia.h>

to your source code.


text:
Q: How to Query in a many to many relationship Room database? I have a many to many relationship Room database with three tables:
First one :
data class Name(
@PrimaryKey(autoGenerate = true)
var nameId : Long = 0L,
@ColumnInfo(name = "name")
var name : String = "",
@ColumnInfo(name = "notes")
var notes: String=""
)

Second:
@Entity(tableName = "tags_table")
data class Tag(
@PrimaryKey(autoGenerate = true)
var tagId : Long = 0L,
@ColumnInfo(name = "tag_name")
var tagName : String = ""
)

Third:
@Entity(
    tableName = "tagInName_table",
    primaryKeys = ["nameId", "tagId"],
    foreignKeys = [
        ForeignKey(
            entity = Name::class,
            parentColumns = ["nameId"],
            childColumns = ["nameId"]
        ),
        ForeignKey(
            entity = Tag::class,
            parentColumns = ["tagId"],
            childColumns = ["tagId"]
        )
    ]
)
data class TagInName(
    @ColumnInfo(name = "nameId")
    var nameId: Long = 0L,
    @ColumnInfo(name = "tagId")
    var tagId: Long = 0L

)

The data class I use for a return object in a Query:
data class NameWithTags(
    @Embedded
    val name: Name,
    @Relation(
        parentColumn = "nameId",
        entityColumn = "tagId",
        associateBy = Junction(value = TagInName::class)
    )
    val listOfTag : List<Tag>
)

This is how I query to get all NamesWithTags:
@Query("SELECT * FROM names_table")
@Transaction
fun getNamesWithTags() : LiveData<List<NameWithTags>>

So the thing I need to do is, I need to Query to return LiveData<List<NameWithTags>> where every NamesWithTags has a list which contains the Tag ID that I Query for.

A: From my interpretation of what you say you need to do, then :-
@Transaction
@Query("SELECT names_table.* FROM names_table JOIN tagInName_table ON names_table.nameId = tagInName_table.nameId JOIN tags_table ON tagInName_table.tagId = tags_table.tagId WHERE tags_table.tagId=:tagId ")
fun getNameWithTagsByTagId(tagId: Long): LiveData<List<NamesWithTags>>

*

*Note the above is in-principle code and has not been compiled or tested, so it may contain some errors.

*A NameWithTags will contain ALL related tags whcih should be fine according to (where every NamesWithTags has a list which contains the Tag ID ), if you wanted just certain Tags in the List of Tags then it's a little more complex, this is explained in a recent answer at  Android Room query with condition for nested object


text:
Q: Volume of tetrahedron / dodecahedron in $m$ dimension What is the formula for calculating volume of tetrahedron in $m$ dimension ?
I am looking for equation dependent on radius of described circle.
I know equations only for $\text{2D}$ and $\text{3D}$ cases.

Tetrahedron:
For $\text{2D}$ it is:
$$
V(r) = \frac{3 \sqrt{3}}{4} * r^2
$$
For $\text{3D}$ it is:
$$
V(r) = \frac{8 \sqrt{3}}{27} * r^3
$$

Dodecahedron :
For $\text{2D}$ it is:
$$
V(r) = \frac{5}{4} \sqrt{ \frac{1}{2} (5 + \sqrt{5}) } * r^2
$$
For $\text{3D}$ it is:
$$
V(r) = \frac{2}{9} \sqrt{3} (5 + \sqrt{5}) * r^3
$$

I was looking fo the fromula for at least few hours without any effects.
Only what I can find is some info about count of verticles, etc.

A: First of all, you must know that this field has been studied through and through, about as thoroughly as the geography of a particular patch of Earth in London, UK, between Downing street and Westminster Bridge. Therefore, whenever you look or ask for it online, you'll get a ton of search results and answers, each containing a whole lot of words that you don't need in front of the words that you do need. Skipping the unnecessary part can be tiresome (I can attest to that myself), so have my answer instead.
Second, all terms in math have precise meaning (unless they have another meaning), and if you use them in a different meaning, you are bound to get garbled search results.
With that in mind, now to the point.
Tetrahedron...
...is a figure in 3 dimensions. A plausible analog in all dimensions is called a simplex. The volume is $\dfrac1{n!}\sqrt{(n+1)^{(n+1)}\over n^n}r^n$, which coincides with your findings for $n=2$ and $3$.
Dodecahedron...
...is a figure in 3 dimensions. A plausible analog in all dimensions does not exist. As to how, turn your face to the nearest load-bearing wall and try to walk through it. That's how much it is impossible. As to why, it is because of math.
For the few values of $n$ that leave a possibility of an analog, the results are:

*

*2D: a pentagon, with the area which coincides with your findings;

*3D: a proper dodecahedron, with the volume which coincides with your findings;

*4D: a so-called 120-cell, with the hypervolume that I will not mention.

That will be all.


text:
Q: How to fetch data from JSON that contain arrays of arrays into object in flutter I am getting json that looks like this:
{"-N42h_BKjWaEZRJyH8vS":[{"Data":"06/2022","imie":"John","DayList":[["7.50","12.00"],["00.00","00.00"],["8.00","16.00"],["00.00","00.00"],["00.00","00.00"],["7.50","15.00"],["00.00","00.00"],["00.00","00.00"],["00.00","00.00"],["8.00","15.25"],["00.00","00.00"],["00.00","00.00"],["7.50","15.00"],["00.00","00.00"]],"surname":"Smith"}]}

Each List inside "DayList" represents separate working day. E.g. ["7.50","12.00"] is simply saying that, work time starts at 7.30 and end at 12. Each day index also represents day of month E.g. index 0 is 01/06/2022, index 1 is 02/06/2022 and so on. The whole List is attached to one person, in this case John Smith.
My Day model looks like this:
class Day {
  String name;
  DateTime dateTime;
  double startTime;
  double endTime;

  Day({
    required this.name,
    required this.dateTime,
    required this.startTime,
    required this.endTime,
  });
}

Anyone have an idea how to create List of objects based on this json?
Maybe there is better way of creating such a json?

A: class DayDatum {
DayDatum({
    this.data,
    this.imie,
    this.dayList,
    this.surname,
});

String data;
String imie;
List<List<String>> dayList;
String surname;

factory DayDatum.fromJson(Map<String, dynamic> json) => DayDatum(
    data: json["Data"],
    imie: json["imie"],
    dayList: List<List<String>>.from(json["DayList"].map((x) => List<String>.from(x.map((x) => x)))),
    surname: json["surname"],
);

Map<String, dynamic> toJson() => {
    "Data": data,
    "imie": imie,
    "DayList": List<dynamic>.from(dayList.map((x) => List<dynamic>.from(x.map((x) => x)))),
    "surname": surname,
};
}

You can use this model to parse data of each object

A: import 'dart:convert';

Data dataFromJson(String str) => Data.fromJson(json.decode(str));

String dataToJson(Data data) => json.encode(data.toJson());

class Data {
  Data({
    this.listOfDays,
  });

  List<personalInfo>? listOfDays;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
        listOfDays: List<personalInfo>.from(json["-N42h_BKjWaEZRJyH8vS"]
            .map((x) => personalInfo.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "-N42h_BKjWaEZRJyH8vS":
            List<dynamic>.from(listOfDays!.map((x) => x.toJson())),
      };
}

class personalInfo {
  personalInfo({
    this.data,
    this.imie,
    this.dayList,
    this.surname,
  });

  String? data;
  String? imie;
  List<List<String>>? dayList;
  String? surname;

  factory personalInfo.fromJson(Map<String, dynamic> json) =>
      personalInfo(
        data: json["Data"],
        imie: json["imie"],
        dayList: List<List<String>>.from(
            json["DayList"].map((x) => List<String>.from(x.map((x) => x)))),
        surname: json["surname"],
      );

  Map<String, dynamic> toJson() => {
        "Data": data,
        "imie": imie,
        "DayList": List<dynamic>.from(
            dayList!.map((x) => List<dynamic>.from(x.map((x) => x)))),
        "surname": surname,
      };
}

also you can use this site to create models directly


text:
Q: What is the meaning of l1 and l2 in EnergyModel() in ns2 In the EnergyModule() method in ns-2 has parameters l1 and l2 , i want to know the meaning of the levels, why we calling it has levels. And what is the purpose of setting it?
EnergyModel::EnergyModel    (
  MobileNode *  n,
  double    energy,
  double    l1,
 double     l2
 )

A: The L1 and L1 are values for changing node color with respect to energy depletion.
        double l1 = 0.5;
        double l2 = 0.2;
     if (srcnode) {
         if (srcnode->energy_model()) {
                 energy = srcnode->energy_model()->energy();
                 initenergy = srcnode->energy_model()->initialenergy();
                 l1 = srcnode->energy_model()->level1();
                 l2 = srcnode->energy_model()->level2();
         }
     }

     int energyLevel = 0 ;
     double energyLeft = (double)(energy/initenergy) ;

     if ((energyLeft <= 1 ) && (energyLeft >= l1 )) energyLevel = 3;
     if ((energyLeft >= l2 ) && (energyLeft < l1 )) energyLevel = 2;
     if ((energyLeft > 0 ) && (energyLeft < l2 )) energyLevel = 1;

     if (energyLevel == 0)
             strcpy(colors,"-c black -o red");
     else if (energyLevel == 1)
             strcpy(colors,"-c red -o yellow");
     else if (energyLevel == 2)
             strcpy(colors,"-c yellow -o green");
     else if (energyLevel == 3)
             strcpy(colors,"-c green -o black");


text:
Q: Is there a faster way to get big dataframe from python to sql server table? I am trying to get nearly 13000000 rows to sql server but it gives resource pool error. Here is the code:
def execute_sql_file(pconnection, pfilepath, **psqlparams):
    cursor = pconnection.cursor()
    f = open(pfilepath)
    full_sql = f.read()
    for key, value in psqlparams.items():
        full_sql = full_sql.replace('#' + str(key) + '#', str(value))
    f.close()
    return cursor.execute(full_sql)

def write_result_to_db(dfsave, pServer='oltp', pDatabase='warehouse',pSchema = 'dbo',pTable =
'tb_table'):
    params = urllib.parse.quote_plus(
    "DRIVER={SQL Server Native Client 11.0};SERVER=" + pServer + ";DATABASE=" + pDatabase + ";
             Trusted_Connection=yes;MARS_Connection=Yes")
    engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
    to_db_connection = engine.connect()

    @sqlalchemy.event.listens_for(engine, "before_cursor_execute")
    def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
        if executemany:
            cursor.fast_executemany = True

    chunknum = math.floor(2100 / dfsave.shape[1]) - 1
    if dfsave.shape[0] > 0:
        dfsave.to_sql(pTable, con=engine, schema=pSchema, if_exists='append', index=False,
                       method='multi',chunksize=chunknum)

    return to_db_connection

This is the function. And after doing mathematical operations, at the end of the calculations, I get df. And when I try to get it to sql server I use this code:
write_result_to_db(df,pTable='tb_table',pServer='testoltp', pSchema = 'dbo',
                   pDatabase = 'warehouse')

But it gives error. Then I tried to divide df and write to sql table like this:
bol = int(tb_result.shape[0] / 50)
for start in range(0, tb_result.shape[0], bol):
    write_result_to_db(tb_result.iloc[start:start +
                       bol],pTable='tb_table',pServer='testoltp', pSchema =
                       'dbo', pDatabase = 'testwarehouse')
    time.sleep(15)

After doing this loop, it gives resource pool error. I think I can't do it with this.
So how can I get dataframe from python to sql server table?

A: try using modin library. You might be able to resolve it
https://github.com/modin-project/modin


text:
Q: NSNotification/Bindings? I am making my way thru the Hilgrass and Kochan books. Doing my own experiments to further my learning I simply want to create a cocoa interface with 4 textfields, 3 that accept numbers and the 4th that displays the sum of the other 3. I can do this using a button to do the calculation however what I want to do is have it autoupdate any time one of the 3 inputs is changed.
I have looked for a lesson that covers this, both in books and online but cannot find one, so either it's really simple and I'm missing something or it's not so simple. It appears the conventional way of doing this is with NSNotifactions but it is maybe possible with bindings as well?
What is the standard way of doing this is cocoa and is there a tutorial that anyone knows of?
Cheers,
Morgan

A: Chapter 7: Key-Value Coding; Key-Value Observing of the Hilgrass' "Cocoa Programming for Mac OS X" or Apple documentation on Key-Value Coding can help you accomplish this task.
Here is my sample xcode project: http://dl.getdropbox.com/u/344540/stackoverflow/AutoAdd.zip .  You can control how the updating happens by using the "Bindings" tab of the Inspector for the NSTextFields in Interface Builder.  There are other gems in that tab too.

A: NSControl (and hence NSTextField) has a notification NSControlTextDidChangeNotification which will be sent whenever the text changes.
So you can register for that notification on your three text fields and then update your calculation field.
I took this a little further, creating a subclass of NSTextField called ActionOnChangeTextField which automatically calls its action whenever the text changes.  So you just set the class of the three text fields to ActionOnChangeTextField and connect the selector to your update calculation method.
@interface ActionOnChangeTextField : NSTextField {

}

@end

@implementation ActionOnChangeTextField

- (void) doTextChangedAction:(NSNotification*)notification;
{
    [[self target] performSelector:[self action]];
}

- (void) awakeFromNib;
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(doTextChangedAction:)
                                                 name:NSControlTextDidChangeNotification
                                               object:self];
}

- (void) dealloc;
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

@end


text:
Q: need help building a query to detect duplicates on multiple columns I have the following table
create table catalog_product_entity_varchar
(
    value_id     int auto_increment comment 'Value ID'
        primary key,
    attribute_id smallint unsigned default 0 not null comment 'Attribute ID',
    store_id     smallint unsigned default 0 not null comment 'Store ID',
    entity_id    int unsigned      default 0 not null comment 'Entity ID',
    value        varchar(255)                null comment 'Value',
)

I want to find all entity_ids where attribute_id = 86 for the same store_id where the value is the same.
For example for the columns attribute_id, store_id, entity_id, value
86, 1, 1, mypath
is duplicate with
86, 1, 2, mypath
but is not duplicate with
86, 2, 1, mypath
The result would be entity_id, store_id, value
Any help is appreciated.

A: You can accomplish this with grouping on your store_id and value in a CTE or subquery to get the dupes and then re-joining the dupes to your  catalog_product_entity_varchar table like so:
WITH CTE_Dupes AS
(
     SELECT store_id, value
     FROM catalog_product_entity_varchar
     WHERE attribute_id = 86
     GROUP BY store_id, value
     HAVING COUNT(1) > 1
)

SELECT C.entity_id, C.store_id, C.value
FROM catalog_product_entity_varchar C
INNER JOIN CTE_Dupes D
    ON C.store_id = D.store_id
    AND C.value = D.value
WHERE C.attribute_id = 86


text:
Q: glutBitmapString/glutStrokeString seem to require const unsigned char* - strings don't work Ubuntu 11.04, G++, freeglut and GLUT.
I don't understand this at all. Here's the error I get:
whatever.cc:315:59: error: cannot convert 'std::string' to 'const unsigned char*' for argument '2' to 'void glutStrokeString(void*, const unsigned char*)'

and if I try glutBitmapString:
whatever.cc:315:59: error: cannot convert 'std::string' to 'const unsigned char*' for argument '2' to 'void glutBitmapString(void*, const unsigned char*)'

Here's the relevant code (I think).
scoreStream << "Score: " << score << "\0";
scoreString = scoreStream.str();

// ...in another method:

glRasterPos2i(0, 0);
glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
glutBitmapString(GLUT_BITMAP_HELVETICA_18, scoreString);

This answer tells me it should work, but it just doesn't.
Quote for those who don't want to jump:
// Draw blue text at screen coordinates (100, 120), where (0, 0) is the top-left of the
// screen in an 18-point Helvetica font
glRasterPos2i(100, 120);
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glutBitmapString(GLUT_BITMAP_HELVETICA_18, "text to render");

(Also, I have tried leaving a direct string like "text to render" in there. No dice.)
whatever.cc:315:64: error: invalid conversion from 'const char*' to 'const unsigned char*'

I am confused. This is my first question on SO, as far as I remember, so apologies if it isn't too well put together. I'll provide any extra information I can.

A: There is no automatic conversion of an std::string to a char const*. However, you can use std::string::c_str() to get the char const* out of an std::string.
e.g. glutBitmapString(GLUT_BITMAP_HELVETICA_18, scoreString.c_str());
Note: The answer you linked to doesn't say that you can use std::string. The example it gives (glutBitmapString(GLUT_BITMAP_HELVETICA_18, "text to render");) uses a string literal, which is an array of char, not an std::string.
Remember that OpenGL is a C library, and std::string doesn't exist in C.


text:
Q: How do I provide method parameter info from a Language Server? I am trying to implement a language server for visual studio code for a language whose method calling is similar to JavaScript (method name plus parameters inside parenthesis).
I would like to provide parameter info (name and type) after the user typed a method and parenthesis based on the position of the cursor inside the parenthesis. For example, when coding in Typescript in vscode, if I type:
Math.pow(

I get a tooltip showing the signature of the method and the first parameter name and type in bold:

then when I enter the first parameter and enter a comma, the tooltip offers details about the second parameter:

I was able to find a way to provide autocompletion on the name of the method, but not the behavior described above for the parameters. Is there an example or a tutorial on how to prompt that tooltip from a language server extension in Visual Studio Code?

A: I found an example in the official php extension source code. I just had to implement a SignatureHelpProvider.


text:
Q: XPages: formating currency in dojo grid When I try to calculate two cell  with onApplyCellEdit() in a dojo grid I get NAN error expecially when is a fraction entry, below is the  formatter function:
 function formatCurrency(value, rowIndex, cell){
    if(value){
        var price =dojo.currency.format(value,{currency:"EUR", locale: 'de-de'});;
        return price;
    }
}

on the onClientLoad event I got:
var grid = dijit.byId('#{id:grid}');
if(grid){
    dojo.require("dojo.number");
    var oldVal
    grid.onStartEdit = function(inCel, inRow){
        var store = dataGrid.store;
        var item = dataGrid.getItem(inRow);
        oldVal = store.getValue(item, inCel.field );

    };

      grid.onApplyCellEdit = function( inVal, inRow, inFld ){
        var store = dataGrid.store;
        var item = dataGrid.getItem(inRow);
        if(inFld =="amount" || inFld =="quantity"){
            var inputPrice =store.getValue(item,"amount")
            var quantity = store.getValue(item,"quantity");
            oldVal = dojo.number.format(oldVal,{locale: 'de-de'});
            if (inVal== oldVal) {
                console.log('No Change Made');
            }else{
                price = dojo.number.parse(inputPrice,{locale: 'de-de'});
                total = (quantity * price);

                store.setValue(item, 'amount', price);
                store.setValue(item, 'totalAmount', total);
                console.log('edit applied');

            }
        }
    };
}

how could I parse und format cell to take in locale: 'de-de' and display cell as currency in EUR.


text:
Q: Chrome Remote Debugging - "Connection Lost" on Lollipop and Marshmallow I'm using Chrome Remote Debugging to debug the WebView in my Android app.
This works fine for me when I run my app on a KITKAT device, and I can inspect all WebView elements (HTML, Javascript, ect.).
But I get a "Connection Lost" message when running my app on Lollipop and Marshmallow.
My Googling failed to find the antidote. Any clue will be HIGHLY appreciated.
I didn't figure out which part of the code to post here, since the question deals with infrastructure.
Many Thanks in advance!


text:
Q: Email Dialog like Call Dialog in Android We can open Call Dialler with Number passed in Intent. So like that, Is there any way to open Email Dialog with to Email ID ?

When User Clicks on Specific TextView, I want to show dialog itself to user like Send Email Using and after choosing appropriate option like Gmail, It opens Gmail with filling to Email Address.

A: Try this
    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.setType("plain/text");

    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
            new String[] { "emailadd" });
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "text");
    startActivity(Intent.createChooser(emailIntent, "Send mail..."));


text:
Q: how GEt image from database Django 3.0 I'm creating Blog on Django 3.0 Framework. so I crashed to a problem with Getting an image from Database. I can upload an image from admin and it's uploading in directory which I want to. When I'm entering image URL to Post I can see directory from Browser inspect. even the name of file but the image didn't show up.
Settings.py
MEDIA_URL = '/uploadfiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, '/uploadfiles')

models.py
STATUS = (
(0,"Drafted"),
(1, "Published")

  )
class Article(models.Model):
    article_title = models.CharField('სიახლის სახელი', max_length=200)
    article_text = models.TextField('კონტენტი')
    pub_date = models.DateTimeField('თარიღი')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    status = models.IntegerField(choices=STATUS, default=0)
    updated_on = models.DateTimeField(auto_now=True)
    slug = models.SlugField(max_length=200, unique=True)
    imagecover = models.ImageField(upload_to='uploadfiles/postimages/', default='img-about1.jpg')

def __str__(self):
    return self.article_title

def Recently_published(self):
    return self.pub_date >= (timezone.now() - datetime.timedelta(7))

Html File

Project Url
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('article/', include('article.urls')),
    path('admin/', admin.site.urls),
    path('grappelli/', include('grappelli.urls')),  # grappelli URLS

]

A: Add this to your url file
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('article/', include('article.urls')),
    path('admin/', admin.site.urls),
    path('grappelli/', include('grappelli.urls')),  # grappelli URLS
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

A: from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('article/', include('article.urls')),
    path('admin/', admin.site.urls),
    path('grappelli/', include('grappelli.urls')),
]+static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root = settings.STATIC_URL)
urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)


text:
Q: How to create non-static, custom content in an AppBar I have a material-ui AppBar that sits up high in the composition, something like this:
<App>
  <AppBar/>
  <Main>
    <Route component={FooPage}/>
    <Route component={BarPage}/>
  </Main
</App>

I would like FooPage and BarPage to be able to "inject" their own content into the AppBar, such as Menus, Selects, etc. -- Without the AppBar or the component that hosts the AppBar to be specifically aware of Foo and/or Bar or any other player that does this.  I can imagine a novel way of doing it by having Foo announce to the world that "Foo is active" and having the FooBar-aware AppBar component, respond by saying "Fine...I'll render a Foo-Menu for you.."
What I want is to be able to do is pull this off without the React version of gnarly switch/case. I am pretty newish to React, and I think this is not specifically a material-ui question, but I wonder...Is there is a direct way of loading children into an AppBar (or ToolBar) where AppBar is agnostic towards its contents? And if so, what does that look like syntactically speaking?

A: AppBar has two properties that can accept elements as values. As such, you could utilize the iconElementLeft or iconElementRight properties to pass in whatever element you want to display.
Check out this JSFiddle as an example:
https://jsfiddle.net/Asalem1/ha6v1714/26/


text:
Q: Can't find proper context for .findNavController() So, I'm working on an Android app etc. I have this Main2Activity with a bottomNavView that helps me switch between ProfileFragment and HomeFragment. The thing is I want to use another navView inside my ProfileFragment, I simulated some kind of TabView so I can see two different fragments inside my ProfileFragment.
So, this is my Main2Activity
public class Main2Activity extends AppCompatActivity{

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

        BottomNavigationView navView = findViewById(R.id.nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_settings, R.id.navigation_new_post,
                R.id.navigation_notifications, R.id.navigation_profile)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }

    public BottomNavigationView getBottomNavigationView(){
        return findViewById(R.id.nav_view);
    }

    public Activity getActivity(){
        return this;
    }
}

This is my ProfileFragment, and here's where the problem is. I can't find the context to use in findNavController() and setupWithNavController():
public class ProfileFragment extends Fragment {

    private ProfileViewModel notificationsViewModel;
    private boolean isLoading = false;

    public ProfileFragment() {
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        notificationsViewModel = ViewModelProviders.of(this).get(ProfileViewModel.class);
        View root = inflater.inflate(R.layout.fragment_profile, container, false);

        BottomNavigationView navView = root.findViewById(R.id.profile_nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_my_posts, R.id.nav_applied_to)
                .build();
        NavController navController = Navigation.findNavController(getActivity(), R.id.profile_nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(new Main2Activity(), navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);

        return root;
    }

}

The error I keep getting: java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
Anyone?
UPDATE: This is the stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.heirup, PID: 17523
    java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
        at android.app.Activity.requireViewById(Activity.java:2772)
        at androidx.core.app.ActivityCompat.requireViewById(ActivityCompat.java:363)
        at androidx.navigation.Navigation.findNavController(Navigation.java:58)
        at com.example.heirup.ui.profile.ProfileFragment.onCreateView(ProfileFragment.java:38)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7081)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
I/Process: Sending signal. PID: 17523 SIG: 9

A: Use findNavController(View v) with parameter root.findViewById(#your nav_host id)