text:
Q: How should I change the R and C values in a snubber circuit when I change motors? I am using a triac circuit to convert a 3 speed motor into a fully variable speed motor.  The triac circuit I'm using is one I lifted from another motor which is already a fully variable speed motor.
The characteristics of the 3 speed motor are different than the variable speed motor, and my question is how can I adjust the snubber circuit R and C values to better match the characteristics of the 3 speed motor.
More detail as follows:
The three speed motor is a PSC 120V, 60Hz, 1.1 Amp motor.  There is a dial to adjust speed between Low, Medium and High.  The main motor winding has three different taps that the hot wire connects to, one each corresponding to the Low, Med and High speed settings. When I have set this fan up for variable speed control with the triac circuit, I have the dial switch set to the highest speed setting.
The variable speed motor is a PSC, 120V, 60Hz, 2.5 Amp motor.  This motor is controlled by a triac circuit, with a variable resistor to adjust the speed of the fan.  The control circuit for this fan is shown in Figure 1.  I am using the same circuit to control the 3 speed fan – everything the same, except a different motor.  The Triac is an ADT25C80H.

Figure 2 shows the voltage profile across the variable speed motor for a half cycle at lowest speed.  You can see that in the first quarter cycle, which in an ideal world would be fully off, the voltage gets no higher than 25V (each division on the chart is 50V).
Contrast this with Figure 3 showing the voltage profile across the 3 speed motor for half a cycle at lowest speed.  You can see here that in the first quarter cycle when the voltage should ideally be off, the voltage across the motor actually gets quite high – approaching 60V before the triac switches on.  This has caused the motor to spin at a higher RPM at lowest speed than I was expecting.  I'm guessing this is due to the snubber circuit R and C values not being optimized for this lower power fan (1.1 Amp vs 2.5 Amp).

So back to my question: How should I adjust the snubber circuit values (R2 and C2 in Figure 1) for the 3 speed motor to get the first quarter cycle of Figure 3 looking more like that in Figure 2 (i.e. closer to being "off", not approaching 60V)?  From what I have read about snubber circuits, the 18 ohm resistor (R2) in my triac cct is on the lower end of what is typically used, and the 0.47uf capacitor (C2) on the higher end. Should I use a higher value resistor? lower value capacitor? if so, by how much?
Pls let me know if there is additional information I can provide that will be helpful (note: I don't have a meter to measure the inductance of the 2 different motors).
Thanks in advance for the help.

A: Belated update on this: I replaced the original triac chip with a snubberless triac chip to see if I could get away without an RC snubber. The answer is that I can, and it now works better (less oscillations on voltage across the motor) than the original triac + snubber.


text:
Q: In JavaScript, is it frowned upon to use the '==' operator?
Possible Duplicate:
JavaScript === vs == : Does it matter which "equal" operator I use?

Noticed this

== is bad. Don't ever use it. On everything else about the language, you'll run into differing opinions.

...while reading an article I found on Hacker News: http://duruk.net/some-web-development-tips/
Why is this frowned upon? What are the alternatives? Is this wrong...
if (foo == bar) {
    //do something
}

A: In general, it's better to use === and !==.  These compare type and value and do not do type conversion.
Whereas == will do a type conversion of one to match the other and then do the comparison so it might report equality on things that are not really the same.
For example:
"0" == 0   // true
"0" === 0  // false

redpajama_set_name: RedPajamaStackExchange


text:
Q: Backup grant privileges for a selected mysql database I have backup the mysql database db1 from a bunch of database hosted on the same server.
Now need to backup only the selected users with privileges who have access to db1 so that I can restore these privileged users to my new server before the db1 restore.

A: Similar problem was already posted on StackOverflow: Backup MySQL users
To find users, who have only access to a given database, use this query (given you have sufficient privileges for the INFORMATION_SCHEMA and mysql database):
SELECT * FROM INFORMATION_SCHEMA.SCHEMA_PRIVILEGES WHERE TABLE_SCHEMA = 'db1';

or
SELECT * FROM mysql.db WHERE db = 'db1';

Also, you can view table-specific privileges for a user:
SELECT * FROM INFORMATION_SCHEMA.TABLE_PRIVILEGES WHERE TABLE_SCHEMA = 'db1';

or
SELECT * FROM mysql.tables_priv WHERE db = 'db1';


text:
Q: Input freeze/lag for a few seconds on Mac Mini M1 I have a M1 Mac mini base model (8 GB RAM, 256 GB drive with 90% filled) that I have been using daily for past week or two. I's pretty much my first real work experience with Mac, since I was a Windows user.
Occasionally when I hit shortcut or even an ordinary key (it happened with letters O, C) for e.g. closing a tab in Chrome, typing a message in Slack, searching for a project in Toggl, the keyboard and mouse freezes for like 2-4 seconds. After it unfreezes, the keys are pressed and action is taken.
Also hitting Caps Lock freezes the inputs in the same way, but I'm not sure if it has the same cause.
It's pretty annoying, I don't know that from Windows
I know I tinker with the system quite a lot and usually have like 5 GB of swap, but I have to have many apps running in the background to make MacOS usable for me. My startup apps:
Karabiner Elements (modifier keys changed + 10 Complex modifications) - this problem happens even if it's not running.

*

*Rectangle Pro

*Middle click

*F.lux

*Toggl

*Shottr

*Alt Tab

*Maccy

*Google Drive

*Logitech Options

*Dropover

*Alfred

*iStatistica

I've got around 20-30 tabs in Chrome opened and ~5 GB of swap. I'm on Monterey 12.6.1.
Do you please have an idea how to fix the freezing? Thanks!


text:
Q: ionic navigation not working and giving cannot find module path This is the error , i have checked everything in my modules and component and there is nothing missing (click to see photo)

A: your second-page import path is wrong please change it
import { SecondPage } from '../second/second'

i hope its work for you.


text:
Q: Two output files share the same path but have different contents: node_modules\.vite\deps_temp\React.js X [ERROR] Two output files share the same path but have different contents: node_modules\.vite\deps_temp\React.js

E:\DGSfrontend\node_modules\esbuild\lib\main.js:1596
  let error = new Error(`${text}${summary}`);
              ^

Error: Build failed with 1 error:
error: Two output files share the same path but have different contents: node_modules\.vite\deps_temp\React.js
    at failureErrorWithLog (E:\DGSfrontend\node_modules\esbuild\lib\main.js:1596:15)
    at E:\DGSfrontend\node_modules\esbuild\lib\main.js:1052:28
    at runOnEndCallbacks (E:\DGSfrontend\node_modules\esbuild\lib\main.js:1468:61)
    at buildResponseToResult (E:\DGSfrontend\node_modules\esbuild\lib\main.js:1050:7)
    at E:\DGSfrontend\node_modules\esbuild\lib\main.js:1162:14
    at responseCallbacks.<computed> (E:\DGSfrontend\node_modules\esbuild\lib\main.js:697:9)
    at handleIncomingPacket (E:\DGSfrontend\node_modules\esbuild\lib\main.js:752:9)
    at Socket.readFromStdout (E:\DGSfrontend\node_modules\esbuild\lib\main.js:673:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12) {
  errors: [
    {
      detail: undefined,
      id: '',
      location: null,
      notes: [],
      pluginName: '',
      text: 'Two output files share the same path but have different contents: node_modules\\.vite\\deps_temp\\React.js'
    }
  ],
  warnings: []
}

Node.js v18.12.1

tried checking and rechecking the file name and package names but didn't work.it occured after I started routing with react-router-dom. It worked before but after some time the error stopped the build and stopped the site


text:
Q: React. Input field with multivalues How can I make or find react component input field with multivalues (really, don't know, how to call it), like tags when I ask question on stackoverflow.

So, I'd like to input one value, press enter, then put another value. Then get an array of submitted values in my form.

A: thanks to Fabrian Schulz comment, chosen this one https://github.com/olahol/react-tagsinput.
To find it, I really need to write "tags input", even though I need it not for tag input.


text:
Q: Proof dealing with the union of cones and the intersection of polar cones I need to solve the following problem:
Let $S_1$ and $S_2$ be two cones.
Let $P(S)$ be the notation for Polar Cone (P) of $S$.
Let $S_1, S_2\in \mathbb{R}^n$.
(i) Show that $S=S_1 \cup  S_2$ is a cone; and,
(ii) Show that $P(S)=P(S_1)\cap P(S_2)$.
Observation: the problem statement does not assume cones' convexity.
I have a draft for (i) but I have no idea on how to do (ii). My try on (i) might be wrong.
Take $\beta\ge0$ and $x\in S_1\cup S_2$. Hence, $x\in S_1$ or $x\in S_2$.
Since both are cones $\beta x\in S_1$ or $\beta x\in S_2$.
Then, $\beta x\in S_1 \cup S_2$. This is the definition of a cone. So, finally, $S_1 \cup S_2$ is a cone.
Is this proof right? How to do (ii)?
Thanks in advance.

A: Your proof for (i) is correct. For (ii) observe that the following statements are equivalent:

*

*$y \in P(S)$.

*$\langle y, x \rangle \leq 0$ for all $x \in S$.

*$\langle y, x \rangle \leq 0$ for each $x \in S_1$ and $\langle y, x, \rangle \leq 0$ for each $x \in S_2$.

*$y \in P(S_1) \cap P(S_2)$.


text:
Q: TypeError: Cannot read property 'Autocomplete' of undefined ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined
TypeError: Cannot read property 'Autocomplete' of undefined
This error keeps popping up when I run my Angular Application. It says something is wrong with my search.component.ts file at line 25. Here is my search component
    /// <reference types="@types/googlemaps" />
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MapsAPILoader } from '@agm/core';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
})
export class SearchComponent implements OnInit {

  autocomplete: any;
  @ViewChild('search')
  public searchElementRef: ElementRef;
  public searchControl: FormControl;

  constructor(private zone: NgZone,
    private mapsAPILoader: MapsAPILoader) { }

  ngOnInit() {
    this.searchControl = new FormControl();

    this.mapsAPILoader.load().then(() => {
        let autocomplete = new window['google'].maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: [],
        componentRestrictions: {'country': 'US'}
      });
      autocomplete.addListener('place_changed', () => {
        this.zone.run(() => {
          const place: google.maps.places.PlaceResult = autocomplete.getPlace();
          this.searchControl.reset();
        });
      });
    });
  }
}

How do I fix this error?
Thanks in advance

A: Check you have activated and imported &libraries=places in your script embed link
<script src="https://maps.googleapis.com/maps/api/js?key={{ config.MAPS_API_KEY }}&libraries=places&callback=initMap&v=weekly" async></script>

A: &libraries=places
need to add to your script tag.
I had same problem when I was trying autocomplete feature of GoogleMap according to this example :
example
Then I changed my script tag like below that fixed the problem.
 <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

A: If the application compiles fine with the error, then it's a TS Lint error. It's because the Lint can't find the properties accessed using the dot . operator. You could work around it using the bracket notation [] instead. Try the following
let autocomplete = new window['google']['maps']['places']['Autocomplete'](this.searchElementRef.nativeElement, {
  types: ["address"]
});

More about property accessors here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

A: You can check your script tag:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={YOUR-API}&libraries=places" async></script>


text:
Q: Does Remote Dektop Virtualization Host provide a benefit in my use case? We have a public facing Remote Desktop Session Host instance for customers of ours to demo and/or setup our CRM software before we send a education team to install the software on site at their business.

We recently upgraded our hardware and are now splitting various products on to separate virtual machines, Also we would like to start using the RD Web Access page to allow us to do things like RemoteApp in the future (but the software is incomparable with it right now, we need to replace a 3rd party control that does not render correctly with RemoteApp).

The VM Host is running 2008 R2 Data Center and the VMs are running 2008 R2 Enterprise. Is there any benefit to installing Remote Desktop Virtualization Host on VM Host? We are not using personal virtual desktops (from what I could tell you can only have one PVD per user and I need them to be able to access any of the three desktops (Program1's, Program2's and Program3's), also to me it seems it would require extra overhead as each user has a full VM running to themselves verses just using a shared terminal session like we do currently), and we currently do not use RemoteApp.
Will I get any benefit installing RD Virtualization Host?

A: Most likely no. RDVH is for VDI type deployments, where Hyper-V will be hosting VDI Desktops, people remote into a RD Session Broker that forward the connection to the appropriate desktop. This doesn't sound much like what you're wanting, at all.


text:
Q: Facebook Activity Feed not working I have used facebook activity feed plugin in my applications,it was worked fine for the past few weeks, now its not working in the website.
I have tested it by my website url in the following facebook url
http://developers.facebook.com/docs/reference/plugins/activity/ it does not bring out the feeds as it before.
Can anyone please suggest me whats the problem happening in Facebook.

A: Try this:  Instead of
< fb:activity site="http://example.com" width="180" height="500" header="true" recommendations="false">

use this:
< fb:activity site="example.com" width="180" height="500" header="true" recommendations="false">

In short: Replacing URL with domain name in the site property.

A: If you use the old iFrame is it working, but the new code series is not.
Change the part that I've put in bold to show your correct FB URL and it should test out just fine. Until the other, newer code is active, I'd skip it.

A: Some times a facebook social plugin will not work properly if the fanpage permissions aren't adjusted to allow "Anyone 13+"
Checkout the image on this blog post, just click to zoom and follow the instructions it will fix this facebook social plugin problem in many instances: http://www.profromgo.com/facebook-social-plugin-working-logged-users

A: i also am having issues with the FB activity displaying properly. if you use IPBs built-in activity feed, and default social sharing settings, it doesn't display. you have to use the iframe code on a custom made block. its how i fixed it. ipb3.3.4

A: I am putting this answer as when I Google I can to this post (even though it is two years old).
Essentially you can show the activity feed by using the Like Box as the activity feed is, by reading this and other forums a nightmare to try to work. Whereas the below takes seconds.
Turns out if you go to the like box page you can do it this way, much easier...
https://developers.facebook.com/docs/plugins/like-box-for-pages/
then tick 'show posts' and that is it.


text:
Q: How to Serialize Hibernate Collections Properly? I'm trying to serialize objects from a database that have been retrieved with Hibernate, and I'm only interested in the objects' actual data in its entirety (cycles included).
Now I've been working with XStream, which seems powerful. The problem with XStream is that it looks all too blindly on the information. It recognizes Hibernate's PersistentCollections as they are, with all the Hibernate metadata included. I don't want to serialize those.
So, is there a reasonable way to extract the original Collection from within a PersistentCollection, and also initialize all referring data the objects might be pointing to. Or can you recommend me to a better approach?
(The results from Simple seem perfect, but it can't cope with such basic util classes as Calendar. It also accepts only one annotated object at a time)

A: I recommend a simpler approach: user dozer: http://dozer.sf.net. Dozer is a bean mapper, you can use it to convert, say, a PersonEJB to an object of the same class. Dozer will recursively trigger all proxy fecthes through getter() calls, and will also convert src types to dest types (let's say java.sql.date to java.utilDate).
Here's a snippet:
MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance();
PersonEJB serializablePerson = mapper.map(myPersonInstance, PersonEJB.class);

Bear in mind, as dozer walks through your object tree it will trigger the proxy loading one by one, so if your object graph has many proxies you will see many queries, which can be expensive.

A: solution described here worked well for me: http://jira.codehaus.org/browse/XSTR-226
the idea is to have custom XStream converter/mapper for hibernate collections, which will extract actual collection from hibernate one and will call corresponding standard converter (for ArrayList, HashMap etc.)

A: What generally seems to be the best way to do it, and the way I am currently doing it is to have another layer of DTO objects. This way you can exclude data that you don't want to go over the channel as well as limit the depth to which the graph is serialized. I use Dozer for my current DTO (Data Transfer Object) from Hibernate objects to the Flex client.
It works great, with a few caveats:

*

*It's not fast, in fact it's downright slow. If you send a lot of data, Dozer will not perform very well. This is mostly because of the Reflection involved in performing its magic.

*In a few cases you'll have to write custom converters for special behavior. These work very well, but they are bi-directional. I personally had to hack the Dozer source to allow uni-directional custom converters.


text:
Q: scp files between hosts through intermediate I have access to 3 machines, A, B, and C. The only possible (ssh) connections are:
A -> B
A -> C
I need to get files from B to C, I can only scp the files from A to B (on A: scp remote local), and then from A to C (on A: scp local remote). However, A does not have enough disk space for some rather large files. Firewall between B and C as well as reverse path from B -> A and C -> A.  and I'm not able to put keys on either B or C for my connection from A to B and C. (long story, another issue)
Is there a way to scp the file on B to C by piping the scp output between A and B directly into an scp from A to C?  such the actual file is not stored locally?
Looking at verbose output, the -3 option seems to send a remote scp command to the remote host B. that fails because of the intermediate firewall blocking the connection.

A: You can use a reverse SSH tunnel for this:
On host A, run:
ssh -R 3000:ip.of.host.c:22 ip.of.host.b

On host B, run
scp -P 3000 /source/file username@localhost:/destination_file

This will create a tunnel, listening on host B, which forwards through host A to host C. So you can use localhost:3000 on host B to make connections to hostc:22.

A: You can use a version of the tar-ssh-tar technique to do this. From server A, run this command:
ssh B 'cd /src && tar cf - file1 file2...' | ssh C 'cd /target && tar xvf -'

This creates a tar-format data stream on B containing the files, pipes that stream back to A through SSH, then to C through SSH, then into the tar program on C which unpacks the files. No files have to be stored on A.
You should set up SSH keys for both B and C, so that you won't be prompted for a password. Two ssh instances prompting for a password at the same time will be confusing.
If this is a long-distance transfer, you could try compressing the tar stream to speed things up:
ssh B 'cd /src && tar zcf - file1 file2...' | ssh C 'cd /target && tar zxvf -'

A: I think the easiest solution is to make a named pipe on pc A. A named pipe is a file that behaves like a standard pipe, i.e. it passes along its content as soon as it becomes available, without storing anything per se. It is a standard means of implementing IPC, Inter Process Communication, on *Nix systems.
  mkfifo my-pipe

creates a named pipe with name my-pipe. The only problem is that you cannot scp a named pipe (the OS will complain about my-pipe not being a regular file). So the way to do it is: in one terminal on pcA, issue the following command:
  cat my-pipe | ssh me@pcC 'cat > /path/to/destination/file'

This command streams the named pipe's content to the pcC, and this is redirected to the destination file.
In another terminal, again on pcA, issue:
  ssh me@pcB 'cat /path/of/source/file' > my-pipe

This command puts to standard output the source file located on the remote pcB, and redirects it to the named pipe.
The named pipe is emptied as soon as material comes in. The end-of-file from pcB closes both connections, to B and to C. Nothing is stored on A. At this point, you may remove the pipe,
 rm my-pipe.

It seems to me quite simple.

A: If you do this frequently, I would suggest adding a proxy command in your ssh config file on server A located in ~/.ssh/config like this:
host serverB
User <user on B>
HostName <hostname of B>

host serverC
User <user on C>
ProxyCommand ssh -q serverB nc -q0 <C hostname> 22

-q is for quiet mode, meaning less output.
Now when you want to copy files from machine A to machine C all you have to do is type scp file1 file2 .. serverC:/some/path You can do this on server C as well if you want to do it in reverse. This is especially helpful if you have different usernames on the different machines, and it can of course also be combined with ssh-copy-id if you don't want to enter your password every time.


text:
Q: Выбор схемы БД при подключении (или выборе данных) в cx_Oracle Доброго времени суток.
Есть необходимость выбрать схему БД при коннекте (или же при выборе данных) к БД Oracle. Но вот где в параметрах подключения указать ее, я не нашел. Буду рад за любую помощь в этом вопросе.
В мануале написано использовать следующие параметры:
cx_Oracle.connect([user, password, dsn, mode, handle, pool, threaded, twophase, events, cclass, purity, newpassword])

Собственно, с первыми тремя все ясно, а вот с остальными... В общем прошу вашей помощи.
P.S. Язык программирования Python, модуль cx_Oracle.
Спасибо.
P.P.S. Хорошо бы метку "cx_Oracle" админы добавили =)

Очень интересное дополнение! В объекте Connection Object написано следующее:
Connection.current_schema
    This read-write attribute sets the current schema attribute for the session.

    Note This attribute is an extension to the DB API definition.

Т.е. есть возможность задавать параметры чтение/запись для текущей схемы БД. А вот как ее выбрать?
A: Установить схему можно, выполнив следующее:
c = cx_Oracle.Connection('login', 'password', 'name db')
c.current_schema = 'name schema'

Поподробней вот тут.

A: Мне кажется, Вы неправильно перевели. "Этот доступный для чтения и записи аттрибут определяет текущую схему для сессии". Т.е. после открытия коннекта вы можете его прочитать, узнав текущую схему, и записать, установив текущую схему.


text:
Q: Find all working IPs on network wifi router ios I am working on a project in which i need to get all the active IPs addresses on the network in xcode using objective c. If any one know how to get all these IPs then kindly guide me. Thanks in advance.

A: Is there an explicit reason you need to use objective-c and xcode? Perfectly good tools already exist to do this kind of work, such as nmap.
If you absolutely have to use objective-c and xcode, look into apples socket libraries. I am not an expert in objective-c, but your program flow would be pulling your current IP address and subnet, calculating how many possible hosts would be on your network, then use Apple's reachability classes to test every IP calculated and save which ones respond.


text:
Q: $n (of a bison's rule) is returning the value of the previous token read I have the following bison's rule on my .y:
constant_definition: T_ID T_EQUAL T_INT_CONST T_SEMICOLON
{
    if(!insert_const($1, T_INTEGER))
    {
        printf("ERROR:... ");
    }
};

my token's:
%token T_ID                   1
%token T_EQUAL                42
%token T_INT_CONST            2
%token T_SEMICOLON            33

...

my union:
%union
{
    int token1;
    int token2;
    int token_int_value;
    float token_float_value;
    int token_boolean_value;
}

%type<token2> T_ID
%type<token_valor_real> T_REAL_CONST
%type<token_valor_int> T_INT_CONST
%type<token_valor_boolean> T_BOOLEAN_CONST

my yylex:
int yylex(void)
{
    token token_read = next_token();

    switch(token_read .token1)
    {
    case T_ID :
        yyval.token2 = token_read.token2;
        break;
    case T_INT_CONST:
        yyval.token_int_value = token_read.token_int_value;
        break;
    case T_REAL_CONST:
        yyval.token_float_value = token_read.token_float_value ;
        break;
    case T_BOOLEAN_CONST:
        yyval.token_boolean_value = token_read.token_boolean_value ;
        break;
    default:
        yylval.token1 = token_read.token1;
        break;
    }

    return token_read.token1;
}

Suppose I have the following sequence of token (token1) read:
5 1 33 39 1(4) 42 2 33 1(5) 42 2 33...
Ever time that bison's rule matches, $1 returns the previous token1's value instead of the secondary token related to T_ID.
For example:
This sequence "1 42 2 33" matches, but $1 is returning "39"
Does anyone know why this could be happening?
Thanks in advance!

A: On the interest of having the answer be in an answer rather than being inside a comment (via @librik):
In yylex, the value being assigned to should be yylval, not yyval.
yyval stores the current value of the left hand side of a semantic action.
yylval stores the currently read token's value.
They're both the same type (YYSTYPE), so assigning wrongly doesn't raise an error.
When you don't set yylval in yylex, the value in yylval keeps the value read by the last token that had been set (in your case, the last token read that wasn't an T_INT_CONST/T_REAL_CONST/T_BOOL_CONST/T_ID). Hence, using yylval instead of yyval will fix it.


text:
Q: Selenium XHR ERROR: Response_Code = -1 I am using the newest version of Selenium RC and firefox 3.5  When I run my test from eclipse I get this error XHR ERROR: Response_Code = -1 Error_Message = Request Error.
Firefox and Selenium RC open up fine, it seems to try to connect to the remote site I want, but then firefox crashes, any ideas?

A: I'm pretty sure this is an issue fixed in trunk (and will come out in the pending 1.0.4 release).  If you download 2.0a5, this includes a 1.0.x compatible Selenium server.  You should be able to drop the -standalone JAR in place and have it work.  If not, building from trunk is your next best bet.
Alternatively, you could try to modify the open command call.  In dynamic languages, such as Ruby, this is fairly straightforward.  open() takes a URL and a boolean as its values.  You'll want to invert the logic for the second param (I think it's false by default, so you'll want true).


text:
Q: How to alert user about unsaved changes in a React npm module library? In one of my components in a React npm module library (a library shared among projects), I need to alert the user about unsaved changes, which means, I have to notify the user before the component unmounts.
I have done a bunch of research, and the only possible way of doing that is through using a router (using like < Prompt /> or setRouteLeaveHook, as SPA doesn't unload the page to navigate between pages.
Since npm modules don't really own the < Router /> components (the React projects using those modules own it), doing anything related to Router seem to yield to the error as shown below:
Error: Invariant failed: You should not use "anything-router-related" outside a <Router>

Is there any way to alert the user about unsaved changes without using react-router in a React npm module library?  Or else how to properly use react router in a react npm module library?

A: Apparently, it's possible to nest Router within BrowserRouter from react-router-dom, all you need to do is to pass the history prop from the BrowserRouter to the Router from react-router-dom.  I have searched around and nobody seemed to mention that one can nest a router within a router.
For the app implementing the library:
render() {
return (

    <BrowserRouter>

        <TopNav />

          <Library history={this.props.history} />

    </BrowserRouter>

)
}

For the Library, grab the history props passed.  Right now, the Alert User Unsaved Changes Prompt can be dealt with within the react-npm-module-library:
render() {
if (this.props.data) {
  return (
    <Router history={this.props.history}>
       <Prompt when message='Are you sure you want to leave?' />
    </Router>
  )
}
}


text:
Q: Layout Manager preferredSize Java I'm still trying to learn how layout managers work. I made a Frame with two JPanels.
The first one contains a textArea with a boxLayout.
The second one contains a flow layout with a button.
I set the preferredSize of each panel accordingly, packed them, but got unexpected results.
import java.awt.*;
import javax.swing.*;

public class LayoutMgrTest
{
    public static void main(String[] args)
    {
        TableBasic frame = new TableBasic();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setVisible(true);

        frame.getContentPane().setLayout(new GridLayout(2,1));

        JPanel controlPane = new JPanel();
        JPanel buttonPane = new JPanel();

        controlPane.setLayout(new BoxLayout(controlPane, BoxLayout.PAGE_AXIS));
        controlPane.setPreferredSize(new Dimension(200, 200));
        controlPane.add(new JScrollPane(new JTextArea()));

        buttonPane.setLayout(new FlowLayout(FlowLayout.LEFT));
        buttonPane.setPreferredSize(new Dimension(100,20));
        buttonPane.add(new JButton("Button1"));
        buttonPane.add(new JButton("Button2"));

        frame.getContentPane().add(controlPane, BorderLayout.NORTH);
        frame.getContentPane().add(buttonPane, BorderLayout.SOUTH);
        frame.setSize(new Dimension(500,500));
        frame.pack();
    }
}

Whatever I do, if I use a grid Layout, it seems to always allocate half of the available space to each control. I have been told that:

The height of each row is dependent on the height of each component
  added in each row.

The buttonpane's height is 20. It's allocating much more than that to it:

What's wrong with this code?
I would like to leave the two JPanels intact please. It's easy to simply add the textbox and the buttons directly to the frame, but I need to do it with JPanels (because I will be adding borders and other things).

A: That's the result of using GridLayout as layout manager. Change it to BorderLayout:
frame.getContentPane().setLayout(new BorderLayout());

For example, this code (I changed a little as possible from the original):
import java.awt.*;
import javax.swing.*;

public class LayoutMgrTest
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        //frame.setVisible(true);
        //frame.getContentPane().setLayout(new BorderLayout());

        JPanel controlPane = new JPanel();
        JPanel buttonPane = new JPanel();

        controlPane.setLayout(new BoxLayout(controlPane, BoxLayout.PAGE_AXIS));
        controlPane.setPreferredSize(new Dimension(200, 200));
        controlPane.add(new JScrollPane(new JTextArea()));

        buttonPane.setLayout(new FlowLayout(FlowLayout.LEFT));
        buttonPane.setPreferredSize(new Dimension(100,40));
        buttonPane.add(new JButton("Button1"));
        buttonPane.add(new JButton("Button2"));

        frame.add(controlPane, BorderLayout.NORTH);
        frame.add(buttonPane, BorderLayout.SOUTH);
        //frame.setSize(new Dimension(500,500));
        frame.pack();
        frame.setVisible(true);
    }
}

Generates this frame:

A:
I set the preferredSize of each panel accordingly,

That is another problem. You should NOT set the preferred size. That is the job of the layout manager. Just add your components to the panels and let the layout manager do its job.
Most compnents have a default preferred size. For some you need to give it a little tip.
For example when using a text area you would give a "suggested" preferred size by using:
JTextArea textArea = new JTextArea(rows, columns);

A: If you use LayoutManager, you should not set a size on a component except the frame.
the size for the components is calculated from the different layout managers.
you find more infos at http://download.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html
in your code, you can add the panel with the textarea to BorderLayout.CENTER. this should solve your problem. the component in BorderLayout.CENTER takes the whole space, except the space needed for the components in NORTH, EAST, SOUTH and WEST.


text:
Q: How do I add unicode to an ID3 tag using ruby? I'm trying to add a unicode title to an ID3 tag (v2.3) of an MP3. Unfortunately, I can't figure out how to do it. According to id3.org's id3v2 page, Unicode strings have to begin with the Unicode BOM.
I'm currently trying id3v2, but the tag saves as gibberish.
I'd like to do it in ruby, but a linux utility would also be acceptable.
Update:
I figured out a solution using the id3lib-ruby gem. It's listed below.

A: Did you try to encode() the string?

A: Update: found a slightly more elegant solution
I figured out a solution that works using the id3lib-ruby gem.
tag = ID3Lib::Tag.new('talk.mp3')
utf16 = Iconv.conv('UTF-16BE', 'UTF-8', str) #UTF-16BE doesn't have BOM
tag << {:id => :TIT2, :textenc => 1, :text => utf16}

utf16 = Iconv.conv('UTF-16', 'UTF-8', str)
utf16_no_bom = utf16[2..-1] #removes the BOM
tag << {:id => :TIT2, :textenc => 1, :text => utf16_no_bom}
This usage comments inside id3lib.rb (line 105) are a bit misleading. If you set :textenc => 1 and include the UTF-16 BOM (\xFF\xFE), then you'll end up with a gibberish character at the beginning of your tag.


text:
Q: Unable to install hadoop on macosx I am unable to run hadoop on my Max OSX.
When I run hadoop version -> nothing happens
When I run sudo hadoop version -> it shows my hadoop version. I read somewhere that I shldn't be using sudo to run hadoop. but anyway this tells me that my hadoop is installed?
Because hadoop version returns nothing, I am unable to open any nodes. Everytime I try to start a node with start-dfs.sh, nothing happens as well. Does anyone knows what's happening here? I've look through all the configuration files multiple times to ensure that I have set them right. Not sure where the problem lies here.

What i did:

*

*Followed the instructions from here
In my config files I edited:

etc/hadoop/core-site.xml:
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://localhost:9000</value>
    </property>
</configuration>

etc/hadoop/hdfs-site.xml:
<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
</configuration>

etc/hadoop/hadoop-env.sh
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home

In fact I managed to run everything before.
I am not sure what I did after tht, but I am unable to start the nodes again. I think it might be because I failed to close my nodes before I shut down my computer before?


text:
Q: Jquery Auto suggestion click able a tag I'm using jquery auto suggestion for search box on site http://www.4songs.pk/. Auto suggestion is working fine. I want suggestions must have click custom A tag. I want suggestion must be click able link.
HTML CODE
<form role="form" id="searchform" method="get" action="http://www.4songs.pk/search">

          <input type="text" autocomplete="off" class="form-control" id="query" name="q" placeholder="Type Track Name and Press Search Button" required>

                <button class="btn btn-success" id="searchsubmit" type="submit"></button>

</form>

JS Code
function doSomething (txt) {
    $('#selection').text ('You selected: ' + txt);
}

$('#query').autocomplete({
    source: function (request, response) {
        var url = 'http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=' + escape (request.term) + '&format=5&alt=json&callback=?';
        $.getJSON (url, function (json) {
            var results = [];
            $.each (json[1], function (ix, val) {
                results.push (''+val [0]+'');
            });
            response (results);
        });
    },
    select: function(e, ui) {
        if (e.which === 13 ) {
            return false;
        }
    },
    delay:200
});
$('#query').keypress (function (ev) {
    if (ev.keyCode === 13) {
        $('#query').autocomplete ('close');
        $('#searchform').submit();
        var txt = $(this).val ();
        doSomething (txt);
        return (false);
    }
});

Fiddle link http://jsfiddle.net/nmz95e7d/

A: Update your select statement to redirect url
 select: function(e, ui) {
            location.href="whereyouwanttogo.com/" + ui.item.label;
        },

Full code
            <form role="form" id="searchform" method="get" action="http://www.4songs.pk/search">

                  <input type="text" autocomplete="off" class="form-control" id="query" name="q" placeholder="Type Track Name and Press Search Button" required>

        </form>

JS
function doSomething (txt) {
    $('#selection').text ('You selected: ' + txt);
}

$('#query').autocomplete({
    source: function (request, response) {
        var url = 'http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=' + escape (request.term) + '&format=5&alt=json&callback=?';
        $.getJSON (url, function (json) {
            var results = [];
            $.each (json[1], function (ix, val) {
                results.push (val [0]);
            });
            response (results);
        });
    },
    select: function(e, ui) {
        //location.href="http://www.4songs.pk/search?q=" + ui;
        window.open('http://www.4songs.pk/search?q='+ ui.item.label.replace(/\s/g, "+"),'_blank');
        if (e.which === 13 ) {
            return false;
        }
    },
    delay:200
});


text:
Q: NodeJS 0.10. No 'data' event emitted on net.Socket I have code to log every connection to my HTTP-server on a socket level and also log any incoming data.
This code was originally written for NodeJS 0.8 and works good there.
No my project is migrated to 0.10.24 and socket logging code stopped working.
Here is my code:
var netLogStream = fs.createWriteStream('net.log');

(function(f) {
    net.Server.prototype.listen = function(port) {
        var rv = f.apply(this, arguments); // (1)
        rv.on('connection', function(socket) { // (2)
            socket.on('data', function(data) {
                data.toString().split('\n').forEach(function(line) { // (3)
                    netLogStream.write('... some logging here ... ' + line);
                });
            });
        });
        return rv;
    };
})(net.Server.prototype.listen);

On 0.10 I can get to (1) and get Socket instance on (2) but I never get to (3). Same time my whole application works fine without any issues.
ADD: My server is created with Express@3.4.x

A: I'm not sure why the results are different between node v0.8 and v0.10, but if I had to guess, I'd be looking at the return value of net.Server.prototype.listen.
According to the documentation, this is an asynchronous method which emits the 'listen' event and invokes its callback when the listening is bound.  You're not looking for that event, but rather, capturing the return value of listen, which for an async function, may not be well-defined.  It's obviously not null or undefined since you don't get a runtime error, but the return value may not be the same between v0.8 and v0.10.
I honestly don't know for sure because I don't do low-level socket coding, but I have 2 suggestions to try:

*

*Since the connection event is emitted from the Server object, perhaps you need this.on instead of rv.on.

*Setup the connection event listener before you invoke listen just to minimize risk of race conditions.

Try this and see what happens:
var netLogStream = fs.createWriteStream('net.log');

(function(f) {
    net.Server.prototype.listen = function(port) {
        this.on('connection', function(socket) { // (2)
            socket.on('data', function(data) {
                data.toString().split('\n').forEach(function(line) { // (3)
                    netLogStream.write('... some logging here ... ' + line);
                });
            });
        });
        return f.apply(this, arguments); // (1)
    };
})(net.Server.prototype.listen);


text:
Q: Display Information through Mysql database I am new here and i want to ask a simple question to all of you as i am a beginner in PHP.
I have created a table in MySQL database with 4 columns named id , stuimg , stuname , studetail.
also i have created a page through which values and image gets stored into these columns. Now my problem is that how can i retrieve all these information stored in these columns and display it on a page (Including Image)
you can check my code and please correct if i am doing something wrong:

    <form action="" method="post">

            <?php
                $p=$_GET['id'];
                include('dbconfig.php');
                $query = "SELECT * FROM aboutstudent where id ='$p'";
                $result = mysql_query($query);
                while ($data = mysql_fetch_array($result))
                {
            ?>

                        Image*:
                        <input name="image" type="file" value="<?php echo $_FILES['image']['name'];?>"  />

                        Name*:
                        <input name="name" type="text" value="<?php echo $data['name'];?>"  />

                        Description*:
                        <input name="des" type="textarea" value="<?php echo $data['description'];?>"  />

            <?php } ?>

    </form>

A: You're trying to post to a new page without the id-variable being set.

A: <input name="image" type="file" value="<?php echo $_FILES['image']['name'];?>"  />

replace it

<img src = "<?php $data['image']; ?>">

and also remove  form while loop
it means write it out of while loop

A: At first, you are directly passing variable to SQL query from $_GET, which is HUGE security issue! See this post or at least use mysql_real_escape_string() like this:
$query = "SELECT * FROM aboutstudent where id ='" . mysql_real_escape_string($p) . "';";

Next, if your dbconfig.php contains correct credentilas AND connect you to database, your code looks fine, except $_FILES['image']['name'], which contains data only when input file is submited. And next, you can't set default value for input type='file'. If you have your image saved in database, use simple $data['image'];, otherwise provide more info.

A: I have implemented your code, and this will work fine

<?php
  $p=$_GET['id'];
  include('dbconfig.php');
  $query = "SELECT * FROM aboutstudent where id ='$p'";
  $result = mysql_query($query);
  while ($data = mysql_fetch_array($result))
  {
?>

         Image*:
         <img src="<?php echo $_FILES['image']['name'];?>"/>

         Name*:
         <input name="name" type="text" value="<?php echo $data['name'];?>"  />

        Description*:
         <input name="des" type="textarea" value="<?php echo $data['description'];?>"  />

        <?php }?>


text:
Q: Registering Scala Functions as Java Functions in Pyspark via UDF1 (struct & case classes) I have a Scala case class as
final case class TestStruct(
    num_1: Long,
    num_2: Long
        )

I have a method that converts string to struct and want to use it in pyspark. I define the following class:
package com.path.test

// other imports including Gson, etc.
import org.apache.spark.sql.api.java.UDF1

class TestJob extends UDF1[String, TestStruct] {
  def call(someString: String): TestStruct = {
      // code to get TestStruct from someString
  }
}

Then I register it in pyspark using
spark.udf.registerJavaFunction("get_struct", "com.path.test")

But when I use df = spark.sql("select get_struct(string_col) from db.tb"), it returns an empty struct. Even when I use df.printSchema() it just shows struct (nullable = true) and not the fields of it (num_1 and num_2)
Other people have shown success with integers (links below), but not with struct / case class data types:
spark-how-to-map-python-with-scala-or-java-user-defined-functions
using-scala-classes-as-udf-with-pyspark
Any help would be appreciated.


text:
Q: When to Expose WCF over Internet I have an internet-facing web-application (built in MVC), and a WCF service that is being used by the web app for data retrieval and some other operations.  Both applications are residing on 2 separate servers under same domain.
My question is, since the web app is facing internet, which means it has a public IP, do I have to do the same for my WCF?
Do I have to expose the WCF via internet?  or, should I set it up using local IP only since I can set-up end-point URL using local IP?
Am I correct to say that web app can communicate with WCF locally while exposing the presentation layer via internet?  That way, WCF is more secured.

A: Which machines do you want to access the WCF services? If only the server side of your web app, then no need for Internet access for WCF. If the client side of your web app needs access, then you need to expose WCF to the Internet.


text:
Q: Regex to match various instances of time When trying to match these various styles of time, i.e.:
const str = `
  12) 9 p.m. A walk away

  06) Noon. Snack

  4) 10:30 a.m. A stroll`;

To extract as:
["9 p.m.", "Noon", "10:30 a.m."]
I'm using this regex expression:
/([0-1]?[0-9]|2[0-3]:[0-5]?[0-9] p.m.|a.m.|Noon)/g
But str.match() is returning as:
["12", "9", "06", "Noon", "4", "10", "3", "0", "a.m."]
Is there an issue with the capture groupings?

A: You could match the hours and make the minutes part optional using (?::[0-5][0-9])?
In your pattern you use a single group for all the alternatives, where you want a group by itself to group a set of alternatives.
The part of a.m. and p.m. could be written as [ap]\.m (note to escape the dot to match it literally)
The whole outer group can be a non capturing group (?: from which you can take the match
To prevent a partial match, you could start the pattern with a word boundary \b
The pattern could be written as:
\b(?:(?:[01]?[0-9]|2[0-3])(?::[0-5][0-9])? [ap]\.m\.|Noon)

Regex demo
If you want to match the 12h clock time:
\b(?:(?:1[0-2]|0?[1-9])(?::[0-5][0-9])? [ap]\.m\.|Noon)

Regex demo

const pattern = /\b(?:(?:[01]?[0-9]|2[0-3])(?::[0-5][0-9])? [ap]\.m\.|Noon)/g;
const str = `
  12) 9 p.m. A walk away

  06) Noon. Snack

  4) 10:30 a.m. A stroll`;

console.log(str.match(pattern));


text:
Q: Can not locate a file in a bash script? I am running a shell script which expects a file in a directory but I can not seem to locate it.
This is my shell script
 #!/usr/bin/env bash

    # expects a file to be present in current directory called INPUT_FILE
    # this is the value set in the jenkins config

        if [ ! -f INPUT_FILE ] ;then
            echo "file ${INPUT_FILE} does not exist"
            exit 1
        fi

And in windows I am running a shell script from a directory like this
D:\scripts> ./all/script.sh

I tried to put INPUT_FILE.csv in scripts folder and also in all folder but it does not seem to work. Where should this file be present?

A: Make sure you have the correct filename.
Windows hides the extension of a file, when you look for INPUT_FILE.csv use
if [ ! -f INPUT_FILE.csv ] ;then
   echo "file INPUT_FILE.csv does not exist"
   exit 1
fi

You tried to use the variable INPUT_FILE. When you want this, try
input_file="INPUT_FILE.csv"
if [ ! -f "${input_file}" ]; then
   echo "file ${input_file} does not exist"
   exit 1
fi

Also note that bash is case sensitive, so INPUT_FILE.csv is different from input_file.csv.

A: It's better to list files first to verify the extension and all file names in the directory then check for the existence of the files.
#!/usr/bin/env bash
ALL_FILES=$(ls -I "*.sh") # This will list all file except .sh
echo "Files in current Directory $ALL_FILES"
INPUT_FILE="INPUT_FILE" # or     INPUT_FILE="INPUT_FILE.csv"
     if [ ! -f $INPUT_FILE ] ;then
            echo "file ${INPUT_FILE} does not exist"
            exit 1
    else
          echo "file  exist ${INPUT_FILE}"
          exit 0

fi

The first advantage, It will list all the file and the second one, If exist you will get the output.


text:
Q: Django Rest Framework - Envelope a Paginated Response I want to wrap an paginated response in an envelope. The Result should look like this.
{
    "data": ["datum 1", "datum 2", "datum 3"],
    "meta": {
        "some": "meta",
        "data": "foo",
    },
    "page": {
        "total": 12345,
        "count": 3,
        "from": 3,
        "to": 6,
        "next": "http://example.com?page=2",
        "prev": "http://example.com?page=0",
    }
}

The custom page format can be achieved by inheriting from PageNumberPagination.
My question is about passing the Metadata. I do not see any way to pass it to the Pagination except some form of in band signaling. Is there a clean(er) way to do this?

A: class CustomPagination(pagination.PageNumberPagination):
    view = None

    def paginate_queryset(self, queryset, request, view=None):
        self.view = view
        return super().paginate_queryset(queryset, request, view)

    def get_meta(self, data=None, **meta):
        return {
            'data_from_view': self.view.__class__.__name__,
            'static_data': settings.ROOT_URLCONF,
            'len_per_page': len(data),
            'dynamic_data_on_thy_fly': meta
        }

    def get_paginated_response(self, data, **meta):
        return Response({
            'links': {
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
            },
            'meta': self.get_meta(data, **meta),
            'count': self.page.paginator.count,
            'results': data
        })


text:
Q: How to write a number animation on the mouse button press event in QML? import QtQuick 1.0

Rectangle
{
  width: 100; height: 100
  color: "red"

   MouseArea
   {
    anchors.fill: parent

    onPressed:
    {
      NumberAnimation
      {
        target: parent.x
        to: 50;
        duration: 1000
      }
    }
  }
}

I expect this code to shift the x position of the rectangle on the button press event, but this does nothing.
Where am I going wrong?

A: You are defining an NumberAnimation in a signal handler, it's not going to work properly. Furthermore, NumberAnimation target should be an item, and here you are targeting a property of an item. Here is your code corrected :
import QtQuick 1.0

Rectangle
{
  id: rect
  width: 100; height: 100
  color: "red"

   MouseArea
   {
    anchors.fill: parent

    onPressed:
    {
        animation.start()
    }

    NumberAnimation
    {
        id: animation
        target: rect
        property: "x"
        to: 50;
        duration: 1000
    }
  }
}

If your rectangle animation should revert when mouse is released, you would like to take benefit of a proper state definition, and animate property "x" at each state change (between default and "pressed" states. Here is a self contained example :
import QtQuick 1.0

Rectangle {
  id: root
  width: 360
  height: 200

  Rectangle
  {
    id: rect
    width: 100; height: 100
    color: "red"

    MouseArea
    {
      id: mouse
      anchors.fill: parent
    }

    states: [
      State {
        name: "pressed"
        when: mouse.pressed

        PropertyChanges {
          target: rect
          x: 50
        }
      }
    ]

    Behavior on x {
      NumberAnimation { duration: 1000 }
    }
  }
}

If you need more complex animation, define a proper Transition. A simple Behavior, here, is more readable I find.

A: Try this code:
import QtQuick 1.0

Rectangle
{
    width: 100; height: 100
    color: "red"

    MouseArea {
        anchors.fill: parent

        onPressed: {
            animation.start();
        }
    }

    NumberAnimation on x {
        id: animation
        running: false

        to: 50
        duration: 1000
    }
}

From docs:

NumberAnimation is a specialized PropertyAnimation that defines an animation to be applied when a numerical value changes.

So, you want not to animate on click, but you want to assign animation to x property of rectangle and start it on click.


text:
Q: Why when saving(ctrl+s) a small python file in VSCode, the save takes a second and temporarily creates a copy of it? When I press ctrl+s to save changes for a python file, the save takes one second. Moreover, in that one second a temporarily copy file is being created, but then deleted. How to fix this thing?
My two files before saving(ctrl+s):

My two files when I click save(ctrl+s):

A: This is a temporary saved file. It records the content of the python file you are saving. It is used to ensure that the content of the python file can be recovered when the computer or vscode is shut down abnormally (such as power failure or manual shutdown). If this file has been saved successfully, this file will disappear, but if it failed, this file will not disappear. It will prompt you whether to restore your python file, and the restored content is extracted from this file.
Hope to answer your questions:)


text:
Q: Re-routing Error asp.net Core with Ocelot (7.0.4) "ReRoutes": [
{
  "DownstreamPathTemplate": "/api/Agent/GetPagedAgents?page={page}",
  "DownstreamScheme": "http",
  "DownstreamHostAndPorts": [
    {
      "Host": "agent.api",
      "Port": 80
    }
  ],
  "UpstreamPathTemplate": "/api/account/user/list/GetPagedAgents?page={page}",
  "UpstreamHttpMethod": []

}]

Here I am trying to Re-route my UpstreamPathTemplate to DownstreamPathTemplate from a query string,
"http://accountmanagement/api/account/user/list/GetPagedAgents?page=1"

this is my query string am sending to my account management service for re-route to my agent service using ocelot.
This is my Controller method in agent service for receiving re-routed path
    [HttpGet]
    [Route("GetPagedAgents")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    public IActionResult Get(string page, string pageSize, string filter,
    string sortBy)
    {
        var Result = _agentServices.GetAll(Convert.ToInt32(page),
Convert.ToInt32(pageSize),filter,sortBy);

          return Ok(Result);
    }

But it's not working. In my OUTPUT window its showing message: Unable to find downstream route for path: /api/account/user/list/GetPagedAgents, verb: GET
that means here it's taking my UpstreamPath as
 Upstream url path is /api/account/user/list/GetPagedAgents

missing the parameter here.
any help will be appreciated. Thank you

A: Did you try to add [FromQuery] attribute?
public IActionResult Get([FromQuery] string page, [FromQuery] string pageSize, [FromQuery] string filter, [FromQuery]string sortBy)
{
...
}

or create a simple model
public class Request
{
   public string Page { get; set; }
   public string PageSize { get; set; }
   public string Filter { get; set; }
   public string SortBy { get; set; }
}

and use it like
public IActionResult Get([FromQuery] Request request)
{
...
}


text:
Q: Permutations of Characters How many strings of five characters use the letters a, b, c, d and do not have the letters bad appearing consecutively and in this order? (Letters can occur any number of times, including not at all.)

A: Total $= 4^5$
Strings containing bad $\newcommand{\1}[2]{{}^{#1}{\mathbb C}_{#2}}= \1314^2$
Subtract those.


text:
Q: URL Schemes in iPhone application I have an iPhone application which I wanted to add URL schemes to. The thing is that I have both a free version and a plus version.
What I would like to do is use the same scheme for both apps, but if the plus version is installed I want to the PLUS version to launch instead of the free version.
Is that possible?
Br,
Paul Peelen

A: No. If multiple apps register for the same URL scheme, it is undefined which app will be activated by the OS. From the iOS Application Programming Guide:

Note: If multiple third-party applications register to handle the same URL scheme, it is undefined as to which of the applications is picked to handle URLs of that type.

Edit: just a thought how you might work around this issue: have your plus version register a second private URL scheme that you do not publish. Then, if your free app is launched from a URL, have it check whether the plus version is present and forward the passed URL to the plus version (via its private URL scheme).


text:
Q: What is the best way to name REST resources when returning same resource but using different DTO? I'm curious what is the best way of returning the same resource but using different DTOs.
For example, I have a user class:
public class User {
   private String name;
   private String surname;
   private String age;
}

The list of users is available under url:
/users

Some other view needs list of users but without age, so, I would like to return list of UserDTO.
public class UserDTO {
   private String name;
   private String surname;
}

What is the proper way of defining url?
/userDtos - this is bad, because I can have more than one DTOs for representing users,
/users/dto - this is also bad
/users?name=true,surname=true - this one is also bad, it indicates that we are filtering the result, but we are not; we're just filtering fields.

For sure someone already had this problem before, but I couldn't find anything on the Internet.

A: A similar concept is called partial response which provide an option to let client to specify which fields to include in the response using the query parameters like:
:
/user?fields=name,surename

Basically you define a syntax for you own query language to represent a selection of fields. Here and Google Cloud API are some examples.
By taking this concept to a more coarse-grained level , you can use query parameter "view" to define different predefined combination of fields such as:
/users              //default view if no "view" query parameter is specified
/users?view=admin   //maybe this view will not show age field
/users?view=hr      //maybe this view only show the fields that are accessible to HR


text:
Q: Get name of element which was just clicked (JSFiddle) I have a page which contains multiple divs with similar but unique names. I also have a Jquery file which is supposed to simply change the classes of the correct div to show or hide.
I have a .click function which waits for any element with an id that starts with replyToComment_
This function will execute if I clicked a class with name replyToComment_1 or replyToComment_spaghetti (although it will only ever be numbers)
When the function executes it needs to get that number on the end of the element that was just clicked and store it into a variable, so if replyToComment_1 was clicked the variable needs to contain 1
Hopefully this makes sense. Here's a JSFiddle which will help. http://jsfiddle.net/frayt/s06m8vc3/4/

A: You can split and take the second element.
var parentCommentId = this.id.split('_')[1];

DEMO

A: In your click handler this refers to the element clicked.  So:
var parentCommentId = $(this).attr('id').split('_')[1];

A: I am not sure yours is the most efficient way to solve this problem, but here goes one solution to your question:
    var id = $(this).attr('id')
    var parentCommentId = id.substr(id.indexOf('_')+1);


text:
Q: How to handle dynamic optional list with with map I do have a spring boot project developed using web-flux which interacts with Dataverse APIs to fetch the details which works fine if dataverse do have the matching records based on the Odata query but returns an exception when it does not have any records in response. Below is the methods for the same.
 @Override
    public Mono<ClientEntity> findPositionWorkerAssignmentByJobPositionId(UUID jobPositionId) {

        ODataEntitySetRequest<ClientEntitySet> request = microsoftOData4Client.getRetrieveRequestFactory()
                .getEntitySetRequest(microsoftOData4Client.newURIBuilder(microsoftOData4Client.getServiceRoot())
                                             .appendEntitySetSegment(positionWorkerAssignmentMapEDMEntitySet.getName())
                                             .expand("cdm_WorkerId", "cdm_JobPositionId")
                                             .filter(String.format(
                                                     "_cdm_jobpositionid_value eq %s and cdm_WorkerId/cdm_workerid ne" +
                                                     " null" +
                                                     " and cdm_JobPositionId/cdm_jobpositionid ne null",
                                                     jobPositionId))
                                             .top(1).build());

        request.setPrefer("odata.include-annotations=OData.Community.Display.V1.FormattedValue");
        Mono<ODataRetrieveResponse<ClientEntitySet>> blockingRequestWrapper = Mono.fromCallable(request::execute);

        return blockingRequestWrapper.subscribeOn(Schedulers.boundedElastic())
                .map(blockingResponse -> {
                    if (blockingResponse.getBody() != null && !blockingResponse.getBody().getEntities().isEmpty()) {
                        return blockingResponse.getBody().getEntities().get(0);
                    } else {
                        return null;
                    }
                }).onErrorStop();
    }

If I do not use if condition to check and directly access blockingResponse.getBody().getEntities().get(0) it results in Index 0 out of bounds for length 0 as it's an empty list and if I do return null in else condition I am getting The mapper returned a null value. How can I fix the issue?
if (blockingResponse.getBody() != null && !blockingResponse.getBody().getEntities().isEmpty()) {
       return blockingResponse.getBody().getEntities().get(0);
} else {
       return null;
}


text:
Q: WP_Query Group by Author and Order each group DESC I'm trying to do a query where I get all the posts from a specific category, order/group them by author and in each group order the posts DESC. In the end the author with the newest post will be a the top of the output list.
This is what I use now, but the posts are not ordered as I need them to be.
$args = array (
 'post_type' => 'post',
 'orderby' => 'author',
 'category_name' => 'cat',
);

$query = new WP_Query($args);

$old_author = 0;
if ($query -> have_posts()) : while ($query->have_posts()) : $query->the_post();

 if($post->post_author != $old_author): //check if author changed
  the_author();
  the_title();
 else:
  the_title();
 endif;

$old_author = $post->post_author;
endwhile;
endif;

I did try to sort the query by date before the query, but the then the author groups doesn't work anymore.
add_action('pre_get_posts','sort_query');
function sort_query( $query ) {
 if( !$query->is_main_query() ) {
  $query->set( 'orderby', 'date' );
 }
}

A: EDIT 2
My idea in edit one did not work, so I scrapped it. This edit I have sorted the returned array using a foreach loop to sort the posts according to date under the specific author, and the author on top has the newest posts.
The code below is tested and working, so you can try the following
$args = array (
 'category_name' => 'cat',
);

$query = new WP_Query($args);

if ( $query->have_posts() ) {

    foreach ( $query->posts as $post_object ) {
        $new_array[$post_object->post_author][] = $post_object;
    }

    foreach ( $new_array as $k=>$v ) {
        echo get_the_author_meta( 'display_name', $k ) . '</br>';

        foreach ( $v as $post ) {
            setup_postdata( $post );
            the_title();
            echo '</br'>;
        }
        wp_reset_postdata();
    }
}

EDIT 1
From your comments, neither the method described in my original answer or
'orderby'   => 'date author';

---SCRAPPING NOTICE---
THIS EDIT HAS BEED SCRAPPED
ORIGINAL POST
I had a lapse in brain power in my comment, I have removed that. Your best possible way would be to try the new orderby parameter syntax (this new syntax came with Wordpress 4.0).
You can try something like this (Untested)
'orderby'   => 'author date',

Remember to adjust your loop accordingly to remove your ordering inside the loop
Just a note, you need to be very careful with your use of pre_get_posts. As you have used it, it will alter all custom queries on all pages, front end and back end


text:
Q: Error while installing oh-my-zsh I'm getting an error while installing oh-my-zsh, doing this:
wget --no-check-certificate https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sh

but at the end i'm getting:
/usr/bin/env: zsh: No such file or directory
sh: source: not found

what am i doing wrong ?
machine: Ubuntu 10.10

A: For other people who might have problems using oh-my-zsh on ubuntu, here's the solution taken from this gist : https://gist.github.com/1498393
First install zsh :
apt-get install zsh

Then install oh-my-zsh using zsh :
wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh

and then you change your shell to zsh
chsh -s `which zsh`

Make then sure you relaunch your terminal session, no need to reboot

A: You (probably) don't have zsh installed. You should run sudo apt-get install zsh before running the script.
If you have zsh installed, you should do the following:
sudo ln -s /bin/zsh4 /bin/zsh

This is because Ubuntu doesn't make this at install time, so you have to Do it yourself™.
Anyway, you should update to Ubuntu 12.04LTS Precise Pangolin, since your version does not have support any more.


text:
Q: Virtualbox DNS stopped working on upgrade to 12.10 I have a Debian image setup on Virtualbox that uses the default NAT to access the internet. It was working fine before I upgraded to 12.10. After I upgraded the DNS lookups no longer work. I still can access ip addresses, but this is not a nice solution.

A: Apparently you need to upgrade VritualBox to 4.2, otherwise it won't work

A: In addition to VBoxManage modifyvm "name" --natdnsproxy1 on, I also had to run VBoxManage modifyvm "name" --natdnshostresolver1 on on each of my VMs to get DNS working.  I found that tip on this page.

A: Got it
VBoxManage modifyvm "VM name" --natdnsproxy1 on
Virtual box has a DHCP server for the NAT engine. Which has a list of registered DNS servers. The above command hides this DNS server list and use the host's resolver settings, thereby forcing the VirtualBox NAT engine to intercept DNS requests and forward them to host's resolver

A: The --natdnsproxy1 on didn't work for me.  :(
But I was able to go into the virtual machine and set my DNS server by hand, and that worked.
My host machine is resolving to the loopback device.  Not sure how or why /etc/resolv.conf got set to the loopback.  My host network connection has a static DNS server configured, that is NOT set to the loopback device.
But everything is resolving fine on my host machine, via the loopback. Odd.

A: I had a similar problem with DNS stop working.  It happened using virtual box version 5.02r102096 running ubuntu server as guest on windows 10 64 bit as host.   The problem occurred after I first activated port forwarding.
Apparently until you activate port forwarding for the NAT it automatically enables port 53 forwarding.    I enabled UDP and TCP forwarding on port 53 and DNS started working again.    It did not work with only UDP forwarded.
I am a little concerned that my host may no longer receive and process port 53 and will fail future DNS lookup as a result but have not tried it.  If this is correct then we probably need to also forward some of the other ports like network Time.
I suspect this is a bug in VirtualBox where it should automatically enable forwarding / sharing some of these common ports unless you explicitly disable them.
I also modified the network interfaces in linux to include the name servers.   /etc/network/interfaces with the line dns-nameservers xx.xx.xx.xx but this had no effect on the problem until port 53 was forwarded.
Note: I tried to post two pictures to make it more clear but the blog required a reputation of 10 so I couldn't.    You can contact me via bayesanalytic.com thanks Joe E.

A: FYI I have grabbed the most recent version of VirtualBox (4.2.16) and it fixes this issue. No CLI commands are necessary to have working DNS on a NAT network.


text:
Q: Core Data: unrecognized selector sent to instance First of all I want to point out that there are many questions that report a similar error, but mine is a different case.
I have these three Core Data entities:

*

*Training, that has a collection of FeatureSet objects

*FeatureSet, that has a collection of FeatureGroup objects

*FeatureGroup, that has only numeric fields

Every entity has its inverse relationship (e.g. FeatureSet has the inverse many-to-one relationship with Training).

These three methods of a helper class perform the insertion of the objects into the managed object context:
// MARK: - Insertion
func insertFeatureGroup(_ groupDict:[String:Any], inSet set:FeatureSet, forData data:String) -> FeatureGroup? {
    guard let group = NSEntityDescription.insertNewObject(forEntityName: "FeatureGroup", into: self.context) as? FeatureGroup else { return nil }

    group.data = data
    group.set = set
    if let min = groupDict["min"] as? Double { group.min = min as NSNumber }
    if let max = groupDict["max"] as? Double { group.max = max as NSNumber }
    if let mean = groupDict["mean"] as? Double { group.mean = mean as NSNumber }
    if let median = groupDict["median"] as? Double { group.median = median as NSNumber }
    if let deviation = groupDict["deviation"] as? Double { group.deviation = deviation as NSNumber }
    if let skewness = groupDict["skewness"] as? Double { group.skewness = skewness as NSNumber }
    if let kurtosis = groupDict["kurtosis"] as? Double { group.kurtosis = kurtosis as NSNumber }
    return group
}

func insertFeatureSet(_ featuresDict:[String:Any], inTraining training:Training) -> FeatureSet? {
    guard let set = NSEntityDescription.insertNewObject(forEntityName: "FeatureSet", into: self.context) as? FeatureSet else { return nil }
    guard let sequenceNumber = featuresDict["sequenceNumber"] as? Int16 else { return nil }

    training.addToSets(set)
    set.training = training
    set.sequenceNumber = sequenceNumber

    if let heartRate = featuresDict["heartRate"] as? [String:Any] {
        if let group = insertFeatureGroup(heartRate, inSet: set, forData: "heartRate") {
            set.addToGroups(group)
        }
    }

    if let rotationRate = featuresDict["rotationRate"] as? [String:Any] {
        if let group = insertFeatureGroup(rotationRate, inSet: set, forData: "rotationRate") {
            set.addToGroups(group)
        }
    }

    if let userAcceleration = featuresDict["userAcceleration"] as? [String:Any] {
        if let group = insertFeatureGroup(userAcceleration, inSet: set, forData: "userAcceleration") {
            set.addToGroups(group)
        }
    }

    if let altitude = featuresDict["altitude"] as? [String:Any] {
        if let group = insertFeatureGroup(altitude, inSet: set, forData: "altitude") {
            set.addToGroups(group)
        }
    }

    if let course = featuresDict["course"] as? [String:Any] {
        if let group = insertFeatureGroup(course, inSet: set, forData: "course") {
            set.addToGroups(group)
        }
    }

    if let speed = featuresDict["speed"] as? [String:Any] {
        if let group = insertFeatureGroup(speed, inSet: set, forData: "speed") {
            set.addToGroups(group)
        }
    }

    return set
}

func insertTraining(activity:String) -> Training? {
    guard let training = NSEntityDescription.insertNewObject(forEntityName: "Training", into: self.context) as? Training else { return nil }
    training.activity = activity
    return training
}

And this is how I perform the fetch:
// MARK: - Fetch
var trainings:[Training]? {
    let request = NSFetchRequest<NSFetchRequestResult>()
    request.returnsObjectsAsFaults = false
    let entity = NSEntityDescription.entity(forEntityName: "Training", in: self.context)
    request.entity = entity

    let sortDesc = NSSortDescriptor(key: "startTime", ascending: true)
    request.sortDescriptors = [sortDesc]

    do {
        guard let trainings = try self.context.fetch(request) as? [Training] else {
            return nil
        }
        return trainings
    } catch {
        print("Error Fetching Trainings: \(error)")
        return nil
    }
}

The problem comes when I try to access the groups property of a featureSet object. Let's support that in some part of my code I fetch all the trainings (and they are fetched successfully):
guard let trainings = <myUtilityClassInstance>.trainings else { return }
guard let myTraining = trainings.first else { return }
guard let mySet = myTraining.sets.first as? FeatureSet else { return }
print(mySet.groups)

The last line of code produces an exception: "unrecognized selector sent to instance 0x1700994b0". If I try to inspect the class of the object mySet, I can see that it's actually a FeatureSet object. This class has a "groups" property. However, it seems like the groups property is not recognised and accessing it produces an exception.
My Xcode project is big and I realise that the problem may be in other parts of the code. I am looking for a suggestion on how to investigate this exception.
PS: I am using the classes (Training, FeatureSet, FeatureGroup) that are generated automatically by Core Data, which include some accessors for the properties (e.g. methods to add/remove a group in a FeatureSet).
Update: the FeatureSet class definition is empty, but these are the extensions that were automatically generated by CoreData:
extension FeatureSet {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<FeatureSet> {
        return NSFetchRequest<FeatureSet>(entityName: "FeatureSet")
    }

    @NSManaged public var sequenceNumber: Int16
    @NSManaged public var groups: NSSet?
    @NSManaged public var training: Training?

}

// MARK: Generated accessors for groups
extension FeatureSet {

    @objc(addGroupsObject:)
    @NSManaged public func addToGroups(_ value: FeatureGroup)

    @objc(removeGroupsObject:)
    @NSManaged public func removeFromGroups(_ value: FeatureGroup)

    @objc(addGroups:)
    @NSManaged public func addToGroups(_ values: NSSet)

    @objc(removeGroups:)
    @NSManaged public func removeFromGroups(_ values: NSSet)

}

A: It turned out that the NSManagedObjectContext object used to fetch the data was deallocated when I was trying to access the FeatureSet's groups property. More info on the matter can be found here.


text:
Q: Zend Framework 1.8+: How to automatically set the application environment? I have been developing an application locally with an application environment setting of development. I think this is being set in the .htaccess file.
Then, I have been deploying new versions to the production server.
I don't want to have to manually change the application environment, by hand, every time I deploy a new version.
How should I do this, so I can set the application environment variable automatically (maybe based on the location that it's being hosted? i.e. myapp.com vs. myapp.local)?

A: You can do this in the either in the server config, virtual host, directory or .htaccess through
 SetEnv SPECIAL_PATH /foo/bin

Ex.
<VirtualHost host1>
SetEnv FOO bar1
...
</VirtualHost>
<VirtualHost host2>
SetEnv FOO bar2
...
</VirtualHost>

For more readings
http://httpd.apache.org/docs/1.3/mod/mod_env.html#setenv
http://docstore.mik.ua/orelly/linux/apache/ch04_06.htm

A:     if (false !== stripos($_SERVER['HTTP_HOST'], 'yourdomain.tld')) {
        $_ENV['APPLICATION_ENV'] = $_SERVER['APPLICATION_ENV'] = 'production';
    }

at the top of index.php

A: I do something like SM, but slight different:
$env = 'development';

if ('www.my-host-name.com' == $_SERVER['HTTP_HOST'] || 'my-server-name' == exec('hostname')) {
    $env = 'production';
}

defined('APPLICATION_ENVIRONMENT') or define('APPLICATION_ENVIRONMENT', $env);
unset($env);

I use my server hostname to determine the environment. I also use my server name because some scripts are run from a cron job and I need this to do the tests.


text:
Q: How to merge data with same id in PHP? My select returns values like this:

It can merge the two lines into one? If so, it is possible in php, or Tsql?
Something like:

This is my select:
           SELECT TRM_ID_TURMA
                 , TRM_HORA_INICIO
                 , TRM_HORA_FIM
                 , TRM_DIA
                 , TRM_VAGAS
                 , MGN_NOME
                 , PROF.USU_NOME AS PROFESSOR
                 , ALU_MATRICULA
                 , USU.USU_NOME NOMEALUNO
              FROM [MGB].[dbo].[TB_TURMA]
             INNER JOIN TB_USUARIO PROF ON PROF.USU_ID_USUARIO = TRM_ID_PROFESSOR
             INNER JOIN TB_NIVEL_TURMA ON NTR_ID_NIVEL_TURMA = TRM_ID_NIVEL
             INNER JOIN TB_MGB_NIVEL ON MGN_ID_MGB_NIVEL = NTR_ID_MGB_NIVEL
             INNER JOIN TB_LOCAL ON LOC_ID_LOCAL = TRM_ID_LOCAL
              LEFT JOIN TB_TURMA_ALUNO ON TAL_ID_TURMA = TRM_ID_TURMA
              LEFT JOIN TB_ALUNO ON ALU_ID_ALUNO = TAL_ID_ALUNO
              LEFT JOIN TB_USUARIO USU ON USU.USU_ID_USUARIO = ALU_ID_USUARIO
             WHERE TRM_ID_ACADEMIA = 27
               AND TRM_STATUS >= 0
               AND (TAL_STATUS IS NULL OR TAL_STATUS >= 0)
             ORDER BY TRM_HORA_INICIO,  TRM_HORA_FIM, TRM_DIA, ALU_MATRICULA, NOMEALUNO

A: Rephrased, I think you say, When TRM_ID_TURMA is the same, pick one row, and join (with comma's) the contents of ALU_MATRICULA and NOMEALUNO.
Is that right?
If so, I think you should solve it in PHP, because that is much easier than in SQL (whichever dialect you happen to use is a mystery to me, I see mysql, sql, oracle and tsql).
Suppose you have run your query, and stored your result in an associative resultset, an array, then try something like this:
$RS = ......your query that results in an array.......
/*
$RS looks like:
array(
 [0] => array("TRM_ID_TURMA"=>48, "TRM_HORA_INICIO" => "10:00:00 000000", ..etc..),
 [1] => array("TRM_ID_TURMA"=>49, "TRM_HORA_INICIO" => "10:00:00 000000", ..etc..)
 [2] => etc etc
)
*/

$tmp = array();
foreach ($RS as $one){
  // $tmp used TRM_ID_TURMA as key, and row as content
  if (isset($tmp[$one["TRM_ID_TURMA"]])){
    // TRM_ID_TURMA already used, add to the fields ALU_MATRICULA and NOMEALUNO.
    $tmp[$one["TRM_ID_TURMA"]]["ALU_MATRICULA"] .= ", " . $one["ALU_MATRICULA"];
    $tmp[$one["TRM_ID_TURMA"]]["NOMEALUNO"] .= ", " . $one["NOMEALUNO"];
  } else {
    $tmp[$one["TRM_ID_TURMA"]] = $one;
  }
}

And your desired result is now in $tmp (with TRM_ID_TURMA as keys)

A: In mysql, take a look at the GROUP_CONCAT function.
SELECT TRM_ID_TURMA, GROUP_CONCAT(USU.USU_NOME NOMEALUNO)
FROM [MGB].[dbo].[TB_TURMA]
GROUP BY TRM_ID_TURMA

Be aware of group_concat_max_len, since your result will be truncated if it exceeds this length.

A: Please read THIS ARTICLE
It shows how to concatenate field values with "FOR XML"
this code comes from this article:
USE AdventureWorks2008R2
SELECT      CAT.Name AS [Category],
            STUFF((    SELECT ',' + SUB.Name AS [text()]
                        — Add a comma (,) before each value
                        FROM Production.ProductSubcategory SUB
                        WHERE
                        SUB.ProductCategoryID = CAT.ProductCategoryID
                        FOR XML PATH('') — Select it as XML
                        ), 1, 1, '' )
                        — This is done to remove the first character (,)
                        — from the result
            AS [Sub Categories]
FROM  Production.ProductCategory CAT


text:
Q: What is the type hint for a (any) python module? I would like to add the (Python3) type hint for a module (class 'module'). The typing package doesn't provide one, and types.ModuleType() is a constructor that returns a module object for a specific name.
Example:
import types
def foo(module: types.ModuleType):
   pass

at least in PyCharm results in

"Cannot find reference ModuleType in types.pyi".

Note that Python typing for module type doesn't answer my question, as it does not explain that ModuleType is both a constructor as well as a type, as answered below.

A:
and types.ModuleType() is a constructor.

That doesn't matter. types.ModuleType is still a reference to a type, just like str and int are. There is no need for a generic Module[typehint] annotation, so types.ModuleType is exacly what you need to use here.
For example, the official Python typeshed project provides a type hint annotation for sys.modules as:
from types import FrameType, ModuleType, TracebackType

# ...

modules: Dict[str, ModuleType]

Don't be confused by the name here; types.ModuleType is a reference to the module type. It is not a separate factory function or something. The CamelCase name follows the convention of that module, and you use that reference because the type object is not otherwise available as a built-in. The types module assigns the value of type(sys) to the name.
If PyCharm is having issues with finding the types.ModuleType stubs, then that's either a problem with PyCharm itself (a bug), or the stubs currently bundled are outdated, or you used an incomplete typeshed set of stubs. See the PyCharm documentation on how to use custom stubs to provide a fresh set.
If that doesn't work, it may be a bug in PyCharm dealing with the concept of exporting type hints. Typeshed currently defines the ModuleType type hints in a separate module, which are then imported into the types.pyi stubfile using the from module import name as name syntax. PEP 484 states that imported type hints are not part of the stub unless you use the as syntax:

Modules and variables imported into the stub are not considered exported from the stub unless the import uses the import ... as ... form or the equivalent from ... import ... as ... form.

It may be that PyCharm doesn't yet correctly handle such cases.


text:
Q: SSL Passthrough with Nginx I have setup a Nginx Ingress to proxy traffic to a Kubernetes cluster I have setup with kubeadm. This seems to be working well.
On the host (where the Master node is setup) I have a number of other services running that are being proxied by another Nginx (publicly facing).
What I want to achieve is route all the traffic to a specific domain (pointing to the cluster) from the first Nginx (facing the public) to the Nginx running in the cluster.
Internet -----> Nginx Public -----> Nginx Ingress -----> Cluster
Nginx Ingress is listening on TLS/SSL traffic.
So I want to passthrough SSL traffic to it via the public Nginx.
I attempted it with the following which didnt seem to work.
upstream cluster {
    server 10.109.70.33:443 max_fails=10 fail_timeout=10s;
}

server {
    listen 80;
    listen [::]:80;

    listen 443;
    listen [::]:443;

    server_name *.dev-new.test.co;

    access_log /var/log/nginx/cluster-access.log;
    error_log  /var/log/nginx/cluster-error.log;

    location / {
        proxy_pass https://cluster;
    }
}

A: You need to add
proxy_set_header Host $host;

in your proxy_pass block. This is needed so the server knows which virtual host you are trying to look into


text:
Q: Extracting maven dependencies on artifact build I need to extract the contents of two jar files into the root directory of my jar file upon the artifact being built. This used to work when I had static dependencies in a libraries folders and simply added them under my Output Structure tab as "Library Files", but now it only includes the jar files rather than the contents of them in the root directory of the artifact.

It confuses me as to why this happens and I've played around with a few parts, but can't find a solution. All I need is the extracted files to be within the output jar file, rather than the libraries just being places in the jar (if I haven't said that a few times already).
All current code, like the pom.xml, can be found on my GitHub repo.
What the jar should look like:
|- lua.class
|- luac.class
|- luajc.class
|- luajc$1.class
|- luajc$InputFile.class
|- luajc$LocalClassLoader
|- META-INF
|- org/luaj
|- config.yml
|- plugin.yml
|- unwrittenfun - Main package

What it ends up looking like:
|- luaj-jme-3.0.1.jar
|- luaj-jse-3.0.1.jar
|- config.yml
|- plugin.yml
|- unwrittenfun - Main package

Any help is appreciated, thanks :)


text:
Q: Monaco editor dynamically resizable I have been searching for a discussion about if it's possible to mimic the html tag textarea's resizing when using Monaco Editor's field all over the Internet but I couldn't find one answering my question.
I'm using the monaco-editor npm package in a React application. Do you have any idea if this is easy to implement?
Thank you in advance!
SOLUTION
With pure css I selected the target html element and just added these properties:
div {
  resize: vertical;
  overflow: auto;
}

A: TL;DR: add automaticLayout: true to your editor's configuration.
NL;PR:
Monaco has a built-in auto resize to parent container functionality:
    createEditorWithAutoResize(){
      this.editor = monaco.editor.create(
            this.editorDiv.current, {
            value: "var x = 0;",
            language: 'javascript',
            automaticLayout: true // <<== the important part
       }
      );
    }
    componentDidMount(){this.createEditorWithAutoResize();}
    constructor(props){super(props); this.editorDiv = React.createRef();}
    render(){return

}

And the CSS for the editor (it avoids rendering the editor for the first time with like 10px height):
    .editor{
     height: 100%;
    }

First tested: v0.10.1, Last tested: v0.32.1
Note:
< v0.20.0: The mechanism does not listen to its container size changes, it polls them.
@nrayburn-tech (Monaco Editor's contributor): Version 0.20 uses MutationObserver for all browsers.  Version 0.21 and later uses ResizeObserver on supported browsers, otherwise, it uses polling as a fallback.

A: For anyone coming here having this issue in a basic web app (html, css, javascript) I've found a solution for the resizing issue I'm experiencing.
I have the monaco editor in a resizable flex container. It will only grow the width, not shrink it, and vertical resizing doesn't seem to work out of the box.
If you use the monaco config "automaticLayout: true" and the following CSS it seems to resize as expected:
.monaco-editor { position: absolute !important; }
I tried the max-width 99% trick but it causes a laggy delayed effect when increasing the width near edge of page.

A: For posterity, the solution I arrived on was to set automaticLayout: false so that I could perform all the layout in a resize event listener.
const placeholder = document.getElementById('placeholder')

const editor = monaco.editor.create(placeholder, {
  value: '// hello world',
  language: 'javascript',
  automaticLayout: false // or remove, it defaults to false
})

// we need the parent of the editor
const parent = placeholder.parentElement

window.addEventListener('resize', () => {
  // make editor as small as possible
  editor.layout({ width: 0, height: 0 })

  // wait for next frame to ensure last layout finished
  window.requestAnimationFrame(() => {
    // get the parent dimensions and re-layout the editor
    const rect = parent.getBoundingClientRect()
    editor.layout({ width: rect.width, height: rect.height })
  })
})

By first reducing the editor layout to 0 we can safely query the dimensions of the parent element without the child (editor) contributing to its size. We can then match the editor to the new parent dimensions. Since this takes place over a single frame, there should be no flickering or lag.

A: this is old question but get the problem to and solved it with react-resize-detector
based on ResizeObserver it feet perfectly to the need (check browser compatibility)
Exemple of component :
import React, { Component } from 'react';
import ReactResizeDetector from 'react-resize-detector';
import * as monaco from 'monaco-editor';

class Editor extends Component {
    constructor(props) {
        super(props)

        this.state = {
            width: 0,
            height: 0,
        }
        this.editor_div = React.createRef()

        this.handle_rezise = this.handle_rezise.bind(this);
    }

    componentDidMount() {
        const editor_model = monaco.editor.createModel('', 'sql');
        this.monaco_editor = monaco.editor.create(this.editor_div.current, this.props.editorOptions);
        this.monaco_editor.setModel(editor_model);
    }

    componentWillUnmount() {
        this.monaco_editor && this.monaco_editor.dispose();
    }

    handle_rezise(width, height) {
        this.monaco_editor.layout({ height, width });
    }

    render() {
        return(

                <ReactResizeDetector
                    handleWidth
                    handleHeight
                    onResize={ this.handle_rezise }
                    refreshMode="debounce"
                    refreshRate={100} />

        )
    }
}

export default Editor;

Hope it's help

A: In my case I'm using that exact CSS but although automaticLayout: true works, I found out overkill (seems to pooling the DOM 100ms interval and I have several editors opened in the document. SO I ended up implementing it manually :
just in case ,  my needs are different: I want the user to resize it the container - in a standard way and cheap (both on code and performance) on libraries and performance. This is what I did:
css container : resize: vertical; overflow: auto
and this js :
function installResizeWatcher(el, fn, interval){
  let offset = {width: el.offsetWidth, height: el.offsetHeight}
  setInterval(()=>{
    let newOffset = {width: el.offsetWidth, height: el.offsetHeight}
    if(offset.height!=newOffset.height||offset.width!=newOffset.width){
      offset = newOffset
      fn()
    }
  }, interval)
}
  const typeScriptCodeContainer = document.getElementById('typeScriptCodeContainer')
  typeScriptCodeEditor = monaco.editor.create(typeScriptCodeContainer, Object.assign(editorOptions, {value: example.codeValue}))
  installResizeWatcher(typeScriptCodeContainer, typeScriptCodeEditor.layout.bind(typeScriptCodeEditor), 2000)

yes, 2 seconds interval and make sure it registers only once. I see there is / was a resize interval on 100ms for the automatic relayout in monaco - IMHO that's too much.
See it in action: https://typescript-api-playground.glitch.me/?example=2

A: if you have a reference to the editor you can just call
editor.layout()
on some resize event.
For example, on window resize:
window.onresize = function (){
    editor.layout();
};


text:
Q: Rudin Functional Analysis Chapter 6 Problem 10 I am currently struggling to solve this problem:
Suppose
$(f_i)$
is  a  sequence of locally  integrable  functions  in  $\omega$ (an open set in $\mathbb R$") and
$\lim_i \int_K |f_i(x)|\,dx = 0$
for every compact $K$ in $\omega$
Prove that then $D^\alpha (f_i) \rightarrow 0$ in $D'(\omega)$ as i goes to infinity, $\forall$ multi-index $\alpha$
I have tried using the distribution definitions and the derivative of a distribution definition, but I am confused with the terminology and I don't see how to actually solve this.
Thanks in advance

A: You only have to show that $\int D^{\alpha} (f_i) \phi$ approaches $0.$ By definition of derivative this reduces to showing that $\int D^{\alpha} \phi (f_i)$ approaches $0.$ This is true because $D^{\alpha} \phi$ is bounded on its support $K.$


text:
Q: Dynamic Generated HTML Table Content I have a HTML Table with multible Table Rows and Columns.
There is a data request to an SQL Database.
The data is then displayed in the table body.
The table headers stay the same.
But now the problem. i don't know why all the data is written in the first column of my html table.
The table headers do not match the data be

let table = < HTMLTableElement > document.getElementById("result1");

let row = table.insertRow(-1);

let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
let cell4 = row.insertCell(3);
let cell5 = row.insertCell(4);
let cell6 = row.insertCell(5);
let cell7 = row.insertCell(6);

cell1.innerHTML = data[i].projekt_nr;
cell2.innerHTML = data[i].projekt_name;
cell3.innerHTML = data[i].inhalt;
cell4.innerHTML = data[i].bauort;
cell5.innerHTML = data[i].standort;
cell6.innerHTML = datum[i];
cell7.innerHTML = nutzer[i];

      Projekt Nummer
      Projekt Name
      Inhalt
      Bauort
      Standort
      Ausleihdatum
      Nutzer

      <input type="text" [(ngModel)]="query_1" (ngModelChange)="search_1()">
      <input type="text" [(ngModel)]="query_2" (ngModelChange)="onSearch_2()">
      <input type="text" [(ngModel)]="query_3" (ngModelChange)="onSearch_3()">
      <input type="text" [(ngModel)]="query_4" (ngModelChange)="onSearch_4()">
      <input type="text" [(ngModel)]="query_5" (ngModelChange)="onSearch_5()">
      <input type="text" [(ngModel)]="query_6" (ngModelChange)="onSearch_6()">
      <input type="text" [(ngModel)]="query_7" (ngModelChange)="onSearch_7()">

See the following picture.
all the data is displayed in the first column. usually the data should match the table headers and the input fields

A:

      Projekt Nummer
      Projekt Name
      Inhalt
      Bauort
      Standort
      Ausleihdatum
      Nutzer

      <input type="text" [(ngModel)]="query_1" (ngModelChange)="search_1()">
      <input type="text" [(ngModel)]="query_2" (ngModelChange)="search_2()">
      <input type="text" [(ngModel)]="query_3" (ngModelChange)="onSearch_3()">
      <input type="text" [(ngModel)]="query_4" (ngModelChange)="onSearch_4()">
      <input type="text" [(ngModel)]="query_5" (ngModelChange)="onSearch_5()">
      <input type="text" [(ngModel)]="query_6" (ngModelChange)="onSearch_6()">
      <input type="text" [(ngModel)]="query_7" (ngModelChange)="onSearch_7()">


text:
Q: .htaccess error "not allowed here" for all for all instructions I am using Debian Lenny and Apache 2. I changed the default .htaccess file with:
AllowOverride AuthConfig

But I always get the error message not allowed here when putting any instructions in the  .htaccess file.
EDIT:
file default:
<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www/

        <Directory />
                Options FollowSymLinks
                Order allow,deny
                Allow from all
                AllowOverride All
        </Directory>

        <Directory /var/www/>
                Options Indexes FollowSymLinks Includes
                #AllowOverride All
                #AllowOverride Indexes AuthConfig Limit FileInfo
                AllowOverride AuthConfig
                Order allow,deny
                Allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined

        Alias /doc/ "/usr/share/doc/"
        <Directory "/usr/share/doc/">
                Options Indexes MultiViews FollowSymLinks
                AllowOverride None
                Order deny,allow
                Deny from all
                Allow from 127.0.0.0/255.0.0.0 ::1/128
        </Directory>

</VirtualHost>

.htaccess:
#Options +FollowSymlinks

# Prevent Directoy listing
Options -Indexes

# Prevent Direct Access to files
<FilesMatch "\.(tpl|ini)">
 Order deny,allow
 Deny from all
</FilesMatch>

# SEO URL Settings
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php?_route_=$1 [L,QSA]

PHP info:
apache2handler

Apache Version = Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny10 with Suhosin-Patch
Apache API Version = 20051115
Server Administrator = webmaster@localhost
Hostname:Port = hw-linux.homework:80
User/Group = www-data(33)/33
Max Requests = Per Child: 0 - Keep Alive: on - Max Per Connection: 100
Timeouts = Connection: 300 - Keep-Alive: 15
Virtual Server = Yes
Server Root  = /etc/apache2
Loaded Modules =

core mod_log_config mod_logio prefork http_core mod_so mod_alias mod_auth_basic
mod_authn_file mod_authz_default mod_authz_groupfile mod_authz_host mod_authz_user
mod_autoindex mod_cgi mod_deflate mod_dir mod_env mod_mime mod_negotiation
mod_php5 mod_rewrite mod_setenvif mod_status

A: You will require a minimum of AllowOverride Authconfig FileInfo Options inside your <Directory> block to get the .htaccess you've posted here to work - mod_rewrite will require FileInfo Options and your <FilesMatch> block requires the Authconfig.
Also: your statement "does not work with AllowOverride All" is mistaken.  You cannot specify a MORE permissive environment than AllowOverride All.  When in doubt, start with that to make sure the rest of your configuration works, then narrow it down more specifically (for security's sake).

A: This option can be used only inside a Directory element. So you have to specify a directory which should be protected.

A: not allowed here is usually caused by trying to set directives in .htaccess file that can only be defined in httpd.conf.
First try
AllowOverride All

In your ower most <Directory> tag to your www folder. Now your .htaccess can work in its full capacity. If this solves the problem, then you can start focusing on security and decrease the number of allowed directives one-by-one.