text:
Q: How do I stop internet explorer's propriety gradient filter from cutting off content that should overflow? I'm using the internet explorer gradient filter in my CSS.
It was all going well until I noticed that images that are supposed to extend beyond their containers overflow:visible; are getting clipped as though the container was set to overflow:hidden;
I have no idea why this would happen, or how to fix it. Can anyone help?
I'm looking at it in IE8 and IE7
This is the css causing the issue, when I comment it out, no more bug:
.box{
filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#b4cfe9', endColorstr='#e4eefc'); /* IE6 & IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#b4cfe9', endColorstr='#e4eefc')"; /* IE8 */
}

A: This may help those who are choosing to drop support for IE7.
IE7 will always have a problem if the element is positioned (relative/absolute/fixed).  In IE8+ the problem goes away if z-index is set to auto.
If you are needing to support IE7, or if you are needing to stack things using z-index, you must settle for a second wrapping DIV.

    Content goes here

Edit 2012-05-29: I have created an example to show how to fix this problem.  I created the example to solve a z-index stacking issue... and it just so happened to fix this problem too (http://jsfiddle.net/ryanwheale/gz8v3/).

A: This works, although it's extra markup.

My content

There is a bonus to this tactic, as you can add multiple gradient boxes and set their heights/widths as a % of the parent, thus emulating the "colour stop" behaviour allowed in safari/moz.
For example:

A: I know this doesn't answer your question in particular, but consider your audience. Are they all just Internet Explorer users, or do they represent natural internet user proportions? If they are not all just IE users (maybe in a corporate/education network) then consider using only the standards-compliant methods, and allowing the application/site to degrade gracefully to a browser that doesn't support it, like IE.
Now, for your question. The reason why it's not working as you expected is that the box does not extend to the end of content, even when overflow is visible. The content simply 'walks' outside the box, but this doesn't make the box bigger. There is no way you can get the box to extend to fit the content, except for not setting the width and/or height properties fixed. In fact, IE had a bug in which instead of overflowing out, the box did extend (this was a bug).
I can recommend one tip though; use min-<width/height> and max-<width/height> instead of width and/or height. They allow you flexible box sizing, with guided boundaries.

A: I set parent div's position to relative and it worked :) (or absolute, works fine too)


text:
Q: Update fields automatically after adding new geometry I have two layers, one for "States" (Polygon) and the other for "Important_Cities_location" (Point). "States" feature class is completed with all attributes. I want to update the state name field automatically in "Important_Cities_Location" when I place them in the respective "States" spatially.
Can anyone help?

A: ArcGIS does not provide a piece of functionality that will let you do this directly out-of-the-box. In other words, there is no standard way for software to check what area a new feature is being created in and then populate a certain field in a feature class with a respective value obtained by performing a spatial join.
Alternative that can get you closer:

*

*Use feature templates for different states with predefined attributes.

*Develop a custom add-in (ArcObjects) which will have this logic (large work).

*Develop a custom Python add-in with some geoprocessing logic which will let you do this in several steps combined into one transaction (as appears to user). I'd go for this.

Of course if you don't need to get a point state attribute updated immediately after clicking a map when creating a point feature, you can wait after you are done with adding all points and then run manually a GP tool Spatial join which will let you transfer the state attribute to the point feature class depending on which state a point is located.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find a data in CSV file with python I have a problem , i wanna to search a data with python from csv file
my code like this
#search process area
area_proses = []
sg1 = []
sg2 = []
sg3 = []
avg = []

#input number you want to search
number = raw_input('Masukan id Spesific Goal\n')

#read csv, and split on "," the line
csv_file = csv.reader(open('C:/xampp_2/htdocs/SkripsiV2/fuzzy/download.csv', "rb"), delimiter=",")

#loop through csv list
for row in csv_file:
    area_proses.append(row[1])
    sg1.append(row[2])
    sg2.append(row[3])
    sg3.append(row[4])
    avg.append(row[5])
    #if current rows 1nd value is equal to input, print that row
    if number == row[0]:
        #masukan data
         print(area_proses,sg1,sg2,sg3,avg)

my problem is when i search with id 11 the output is like this:
(['area_proses', 'Service Delivery'], ['sg1', '3.71'], ['sg2', '3.48'], ['sg3',
'3.30'], ['avg', '3.50'])

but when i search id 12 the output is like :
 (['area_proses', 'Service Delivery', 'Incident Resolution and Prevention'], ['sg
    1', '3.71', '3.83'], ['sg2', '3.48', '3.65'], ['sg3', '3.30', '3.70'], ['avg', '
    3.50', '3.73'])

How i can solved this problem?
Download.csv
"id","area_proses","sg1","sg2","sg3","avg","fuzzy",
"11","Service Delivery","3.71","3.48","3.30","3.50","0.00000000000",
"12","Incident Resolution and Prevention","3.83","3.65","3.70","3.73","0.00000000000",
"13","Service System Development","3.93","3.29","3.26","3.49","0.00000000000",
"14","Service System Transition","3.00","3.43","0.00","3.22","0.00000000000",
"15","Strategic Service Management","3.48","3.86","0.00","3.67","0.00000000000",
"16","Configuration Management","3.14","3.57","0.00","3.36","0.00000000000",
"17","Measurement and Analysis","2.93","3.18","0.00","3.06","0.00000000000",

A: Try using the pandas library. Install it, then do:
import pandas as pd
df = pd.read_csv('csv_file.csv')

df[df['id'] == number]

A: Just change 'rb' to 'r'
fopn = open(file_loc, "r")
   csv_file = csv.reader(fopn)
   for row in csv_file:
       if number == row[0]:
          print(row)


text:
Q: Get and work at the line of java exception Say we have 6 lines of code written in Java and x exception can occur any time at any line out of 6.
How I can catch only that line of code and work on that in a catch block.
If an exception occurs at the 2nd line it shall get that line and work on that.
Please let me know if this is possible in Java.
Thanks,

A: Try using
x.getStackTrace()[0].getLineNumber();

along with a switch case block

A: Note that using exceptions to control the flow of your program is usually not the best approach. But if you really want to do it, then maybe this could work?
int stepCompleted = 0;

try {
    doFirst();
    ++stepCompleted;
    doSecond();
    ++stepCompleted;
    ...
} catch (Exception e) {

    switch(stepCompleted) {

        case 0:
            // Do stuff ...
            break;

        case 1:
            // Do stuff ...
            break;
        ...
}


text:
Q: HttpResponse status code 400 android I am sending a GET request to the server when I login. I am expecting a 200 response, but I get a 400 status code when I login. Later if I exit the app and relaunch it, I get a 200 status code.
What I want to do:

*

*I login to a website.

*I get a deviceId, EncodedAccountName and hostUrl in response.

*I get redirected to another url which consists of these parameters in the url. I then match the redirected url with a string and if it matches I stop the webview loading.

*When the redirected url matches my string I am supposed to get other parameters from the response along with a 200 status code where I get a 400 instead.

Iam confused with this behaviour:
Here is my code:
Login.java
myWebView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon)  {
        super.onPageStarted(view, url, favicon);
        loadingFinished = false;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if(!isRedirected) {
            loadingFinished = true;
        }

        if(progressBar!=null && progressBar.isShowing()) {
            progressBar.dismiss();
        }
        url= view.getUrl();
        redirected= Uri.decode(url);

        if(loadingFinished && ! isRedirected && redirected!=null && redirected.contains("redirect_uri="+endpointHost+"/AuthorizeDevice/index/"+deviceId+"?{StandardTokens}")) {
            Utility.ProgressDialogFragment progDialog = new Utility.ProgressDialogFragment();
            progDialog.show(getFragmentManager(), "Wait");
            myWebView.stopLoading();

            //String authorizationContentString =  AuthenticateDeviceEndPoint+ "?encodedAccountName=" + encodedAccountName + "&deviceId=" + deviceId + "&hostUrl=" + hostUrl;
            // authorizationContentString = authorizationContentString.replace("|", "%7C");

            //UserInformation userInfo;
            JSONParser parser = new JSONParser();
            Object register;
            try  {
                // userInfo
                // String responseData= new AuthenticateDevice(Details1.this,myprogressDialog).execute(authorizationContentString).get();
                String responseData = new AuthenticateDevice(Details1.this, progDialog, encodedAccountName, deviceId, hostUrl).execute(AuthenticateDeviceEndPoint).get();
                register = parser.parse(responseData);
            }

AuthenticateDevice.java
public class AuthenticateDevice extends AsyncTask<String, String, String> {

    public Context mContext;
    String responseBody = "" ;
    ProgressDialog dialog;
    Utility.ProgressDialogFragment progDia;
    FragmentManager man;
    String encodedAccName, deviceId, hostUrl;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        /* progDia= new Utility.ProgressDialogFragment().newInstance();
        progDia.show(man, "wait");
        dialog=new ProgressDialog(mContext);
        dialog.setTitle("Processing..");
        dialog.setMessage("Please wait..");
        dialog.show();*/
    }

    public AuthenticateDevice(Details1 myContext, ProgressDialogFragment progDialog, String encodedAccountName, String deviceId, String hostUrl) {
        mContext = myContext;
        this.progDia = progDialog;
        this.encodedAccName = encodedAccountName;
        this.deviceId = deviceId;
       this.hostUrl = hostUrl;
    }

    @Override
    protected String doInBackground(String... params) {
        String Url = params[0];
        if(!Url.endsWith("?"))
            Url += "?";
        List<NameValuePair> nameValuePair = new LinkedList<NameValuePair>();
        nameValuePair.add(new BasicNameValuePair("encodedAccountName", encodedAccName));
        nameValuePair.add(new BasicNameValuePair("deviceId", deviceId));
        nameValuePair.add(new BasicNameValuePair("hostUrl", hostUrl));
        String paramString = URLEncodedUtils.format(nameValuePair, "utf-8");
        Url += paramString;

        HttpResponse response =null;
        String resultString = "";

        // Creating HTTP client
        HttpClient httpClient = new DefaultHttpClient();
        // Creating HTTP Post
        HttpGet request = new HttpGet(Url);

        try {

            response = httpClient.execute(request);
            if(response.getStatusLine().getStatusCode()== 200) {
                HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        InputStream inputStream = entity.getContent();
                        responseBody = convertToString(inputStream);
                        return responseBody;
                    }
                }

            } catch (ClientProtocolException e)  {
                e.printStackTrace();
            } catch (IOException e)  {
                e.printStackTrace();
            }
        return  responseBody;
    }
}


text:
Q: SharePoint Server Publishing Infrastructure" feature workaround? I am running Sharepoint 2010 Foundation.. I have been trying to locate SharePoint Server Publishing Infrastructure" features... This feature does not seem to be available on the Foundation version... Is there any work around for this? As I would like to make use of the ability to limit audiences and such like Any help would be most appreciated. Thank you in advance.
Steve.C

A: Targeting audience is also dependent on the User Profile service application, which again is not available in Foundations. Beyond this point, the Publishing Infrastructure is really a complex endeavour with many features, content types, web parts deployed with it.
In your situation, you might want to consider relying on either Permissions Levels assigned to various Security Groups, or Permissions Masks (e.g. in combination with SecurityTrimining sections) to replace Audiences, or user People/Groups and filter in your components based on that.  Examples could be found http://raiumair.wordpress.com/2009/08/05/security-trim-control/ or explanations http://sharepointgauravgoyal.blogspot.ch/2011/04/security-trimmed-controls-in-sharepoint.html
Also the use of [Me] via SharePoint Designer filter of the DataView web part could help.


text:
Q: In sodium lamps, don't we need low pressure gas for collisional excitation to occur? I have been reading about collisional excitation in Physics for Scientists and Engineers by Knight. What I am confused about is that it says that collisional excitation is the predominant method of excitation in electrical discharges such as fluorescent lights, street lights, and neon signs.
An example is used of placing low pressure mercury gas in a tube. A high voltage between electrodes at each end of the tube causes the gas to ionise, creating a current in which both ions and electrons are charge carriers. If pressure is too high then the mean free path between electrons is too short for the electrons to gain enough kinetic energy to excite the atoms.
Later in the text the example of a high pressure sodium lamp is given, where an electrical discharge is created in sodium vapour.
I thought sodium lamps worked on the principle of collisional excitation, but in this case, wouldn't we require low pressure gas? Or do high pressure sodium lamps work differently?


text:
Q: When typing something in JTextField, the text is randomly appearing and disappearing so I wrote a simple game in Java and programmed the gui for it, but I have trouble with a text field, that is used for writing commands. When I hit "run" in Netbeans, the game runs smoothly, but then I start typing the command in the field and with every letter I hit, the parts of the text I already wrote are randomly appearing and disappearing. Like :
this

the first one is before I start typing, the second one should say morning and the third one should say good morning. And everytime I add another character the text changes and some parts appear and some disappear. Why is it doing this?


text:
Q: R: Subsetting with two variables This is a follow-up to: R: Subsetting on increasing value to max excluding the decreasing
The posted solution works and now I would like to add a low cutoff based on a second variable.   Thus far I'm not certain about how to approach this with data.table.  As an example, I would like to restrict output to max of B and all values after the first instance of D == 1 by TrialNum. I assume this means extracting and using the index (using which?) associated with the low cutoff of D.
TrialNum,Obs ,A,B,C,D
1,1,23,1,23,1
1,2,21,2,21,2
1,3,14,3,14,1
1,4,34,4,34,3
1,5,32,5,32,2
1,6,21,3,21,1
1,7,16,5,16,3
1,8,18,2,18,1
2,1,26,1,26,1
2,2,11,2,11,2
2,3,23,3,23,1
2,4,12,4,12,1
2,5,3,2,3,1
2,6,4,3,4,3
2,7,22,1,22,1
2,8,15,2,15,1

Expected output,
TrialNum,Obs,A,B,C,D
1,2,21,2,21,2
1,3,14,3,14,1
1,4,34,4,34,3
1,5,32,5,32,2
2,2,11,2,11,2
2,3,23,3,23,1
2,4,12,4,12,1

So, it's just the first instance of the low cutoff. I don't which to lose data where D drops below threshold after identifying the starting point.  Like the solution posted yesterday, I've tried variations of using which in the expression to capture both max(B) and the low cutoff associated with D.
A data.table solution is preferable because it seems currently data.table and dplyr are incompatible on Windows R3.2.0.

A: To solve your problem, think about how to find the row numbers you are
after.
Assume for the moment our dataframe has just one TrialNum in it. In your previous question, you learned that to find the row with the maximum value of B, you can use which.max(B).
Now you want to find the row where D is 1, so you can use which(D==1). Now, if multiple rows equal 1, which will return multiple indices (see ?which), so you can use [1] to get just the index of the first occurence. Since you don't want to include the D==1 row itself, add 1 to the index: which(D==1)[1] + 1.
When you have these two numbers, you just want all rows in between, i.e. (which(D==1)[1] + 1):which.max(B).
Then combine with by=TrialNum to ensure that your dataframe only has one TrialNum in it:
x[, .SD[(which(D==1)[1] + 1):which.max(B)], by=TrialNum]

(Note - what will you do if there is no row where D==1? You will have to think about how to handle that).


text:
Q: How to deploy symfony rest api project in hosting without third-party applications? I am trying to deploy symphony api project in hosting.
Until now, all the projects I have done have been pure php, uploading to hosting is simple and everything always works perfectly.
The situation with symfony is tragic and impossible for me, uploading the code just does not work.
I'm really very disappointed with the framework... deploying react, angular is so easy and here it's just ridiculously impossibly hard...
My question is not specific but I'm sure if there is a good answer it will be useful for thousands like me!
Can someone help me with this please? Any tutorial, video etc.
For 3 days I have been searching for information on Google and YouTube from morning to night all day like crazy.
I would appreciate it if someone could just send me a link to a blog tutorial or a video that works without third party applications. I am really tired...

A: Symfony is alive and well, just had a major developer conference in Paris days ago. Symfony has a new minor release every 6 months, a new version 6.2 will be released in the coming days.
Just make sure to follow the information for deployment linked above as well as the setup requirements: https://symfony.com/doc/current/setup.html#symfony-tech-requirements. Perhaps you are trying to run Symfony 6.1 with PHP lower than 8.1?
As to other backend frameworks like Laravel (which is based in part on Symfony): Almost everything in PHP land nowadays is using Composer for easy installation. Any hosting environment that provides SSH access should allow you to setup/use Composer.
A common pipeline to roll out projects can be IDE > GitHub > server. You can however use SFTP as well, just make sure that the program you are using follows the .gitignore file and doesn't try to upload everything. Afterwards run Composer and Yarn/NPM to install everything that your project needs.

A: the whole problem was in the version of composer, which is 1.0.0 in the hosting, which creates hundreds of errors and it is simply impossible to install the project written on the latest version.
All I had to do was manually install the latest version of composer on the hosting.
Then I install the project using the composer phar file
php ~/composer.phar install
instead of the default one which from the hosting is the oldest version 1.0.0 and bring impossible to fix problems.
If anyone has a similar problem just check the composer version in the hosting.


text:
Q: How can I give special character to php from html without displaying it in website? I want to give some representation to some links in html so that those representation could be used to release links according to that representation.
I have created some of the link, but when you click those links it will show a modal to fill the from and those users are given links whose details match to my database. But, the problem is that, I am not able to give specified links.
This is my html code:
Assignment 2

                        Zip file

                    2.18 MB
                    June 21, 2019

                    Assignment 3

                        Zip file

                    2.65 MB
                    June 27, 2019

                    Assignment 4

                        Zip file

This is my js code for modal:
        document.querySelector('.g2').addEventListener('click', function(){
            document.querySelector('.bg-modal').style.display = 'flex';
        });

        document.querySelector('.g3').addEventListener('click', function(){
            document.querySelector('.bg-modal').style.display = 'flex';
        });

        document.querySelector('.g4').addEventListener('click', function(){
            document.querySelector('.bg-modal').style.display = 'flex';
        });

This is my php:
if($user){
                if($user['firstname'] === $firstname && $user['lastname'] === $lastname && $user['std_id'] === $std_id){

                    ob_start();

                    $url = 'https://google.com';

                    while (ob_get_status())
                    {
                        ob_end_clean();
                    }

                    header( "Location: $url" );

                }

As in the following codes.. main problem is that either I click Assignment 2 or 3 or 4, after authorization, every link(ie, Assignment 2, Assignment 3, Assignment 4) are open to https://google.com . Here what I want is that when I click Assignment 2, it should open different link.
If I cannot explain it properly please ask.. I would appreciate it.

A: As I understand, your problem is you are getting the same url:https://google.com when you click on any hyperlink Assignment2 3 or 4. If I am correct so the problem is you are using a variable $url and you have already set this to https://google.com and you are using header to relocate page. This is same as header( "Location:https://google.com" ) every time you click on any link. The thing you have to do is to dynamically change url(value of variable) link and then use header function you will always get associated link on click.


text:
Q: Does anyone knows a REST based CSS minifier? I have a handler that needs to read the content of a CSS file, and then output the content minified.
So thats why I'm looking for a minifier that would work as a REST api, so I can send content, and get back the response to output this content to the user.
Something like the Closure compiler REST service, but for CSS.

A: Check this (http://reducisaurus.appspot.com/css?url=YOUR_CSS_FILE_URL). Not actually a web service, but very close. Googlecode

A: Check this website - http://cssminifier.com/
They offer an API to use with POST requests

A: Check out http://cnvyr.io - also has bundling and image thumbnailing etc


text:
Q: Can't run Sound program I wanted to try to run one example of "Playing sound in Java" but its not working, throwing me an Exception!
This is The JFrame Class
public class JFrame {
JFrame frame = new JFrame();
}

Here is the SoundEffect enum.
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public enum SoundEffect {
SONG("Sound.wav");
 public static enum Volume {
      MUTE, LOW, MEDIUM, HIGH
   }
 public static Volume volume = Volume.LOW;
   private Clip clip;
   SoundEffect(String SONG) {
          try {
             URL url = this.getClass().getClassLoader().getResource(SONG);
             AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
             clip = AudioSystem.getClip();
             clip.open(audioInputStream);
          } catch (UnsupportedAudioFileException e) {
             e.printStackTrace();
          } catch (IOException e) {
                 e.printStackTrace();
          } catch (LineUnavailableException e) {
                 e.printStackTrace();
              }
       }
   public void play() {
          if (volume != Volume.MUTE) {
             if (clip.isRunning())
                clip.stop();
             clip.setFramePosition(0);
             clip.start();
          }
       }
   static void init() {
          values();
   }
}

The SoundEffectDemo class.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class SoundEffectDemo extends JFrame {

public SoundEffectDemo(){
    SoundEffect.init();
     SoundEffect.volume = SoundEffect.Volume.LOW;
     Container cp = this.getContentPane();
      cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
      JButton btnSound1 = new JButton("Sound 1");
      btnSound1.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
             SoundEffect.SONG.play();
          }
       });
      cp.add(btnSound1);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setTitle("Test SoundEffct");
      this.pack();
      this.setVisible(true);
}
public static void main(String[] args) {
    new SoundEffectDemo();
}

}

Everything seems to be normal, there are no red lines. But whenever i try to run it, its giving me that.
Exception in thread "main" java.lang.ExceptionInInitializerError
at SoundEffectDemo.<init>(SoundEffectDemo.java:12)
at SoundEffectDemo.main(SoundEffectDemo.java:30)
Caused by: java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(Unknown Source)
at javax.sound.midi.MidiSystem.getSequence(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at SoundEffect.<init>(SoundEffect.java:20)
at SoundEffect.<clinit>(SoundEffect.java:11)
... 2 more

Any idea how to fix that?


text:
Q: Programa não cumpre o fluxo esperado lendo e imprimindo entrada #include <stdio.h>
#include <stdlib.h>
int main()
{

        int num1, num2, num3;
        printf("Digite o numero A e numero B para saber o resto da divisao resultante da divisao entre eles:\n");
        printf("NumeroA: "); scanf("%i\n", num1);
        printf("\n");
        printf("NumeroB: "); scanf("%i\n", num2);
        printf("O resto da divisao e: %i", num1 % num2);
        return 0;
}

Em vez de imprimir o resto, SO imprime o primeiro, o segundo printf() e o scanf().
O que estou fazendo de mal?
Também gostaria de saber como posso indicar uma variável num printf() (como eu sei Python vou tentar explicar e se alguém souber penso que consegue entender)
n = int(input("Digite um numero: "))
m = int(input("Digite outro numero: "))
print (" Imprimiu o numero {} e {}".format(n, m))

Sou novo e nisto e tenho apenas 15 anos D, usem linguagem acessível por favor.

A: O maior problema é que não está passando o endereço da variável onde deve ser colocado o valor no scanf(). Esta função precisa saber onde deve colocar o valor digitado. Passar o valor que está nela não serve para nada. Funciona diferente do Python que o valor é retornado na função.
O operador & pega o endereço da variável. É isto que precisa mudar no código
Na verdade esta função até retorna um valor indicado se der certo ou não a leitura. Em geral em exercícios assim a gente deixa isso pra lá, mas o correto é verificar se a operação foi bem sucedida. Veja a documentação da scanf().
#include <stdio.h>

int main() {
    int num1, num2;
    printf("Digite o numero A e numero B para saber o resto da divisao resultante da divisao entre eles:\n");
    printf("NumeroA: "); scanf("%d", &num1);
    printf("\n");
    printf("NumeroB: "); scanf("%d", &num2);
    printf("O resto da divisao e: %d", num1 % num2);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Já está usando o printf() como deve usar. Pode passar uma expressão ou uma variável sem problemas. O que está no % é o local que vai cada argumento com a formatação específica. Veja a formatação.
Melhorei mais algumas coisas, preste atenção ao código.
Recomendo aprender as coisas de forma estruturada e com material bom, especialmente em C. Na tentativa e erro não dá certo.

A: Faltou o & na leitura dos valores no scanf. Isto é necessário porque o scanf recebe o local na memória onde tem de colocar os valores lidos, que é o que o operador & dá.
Faça então assim:
#include <stdio.h>
#include <stdlib.h>
int main()
{

        int num1, num2, num3;
        printf("Digite o numero A e numero B para saber o resto da divisao resultante da divisao entre eles:\n");
        printf("NumeroA: "); scanf("%i", &num1);
        printf("\n");
        printf("NumeroB: "); scanf("%i", &num2);
        printf("O resto da divisao e: %i", num1 % num2);
        return 0;
}

Não deve também ter o \n no scanf caso contrário a leitura dos números não será normal.
A formatação mais normal para números é %d, mas %i funciona também, podendo reconhecer valores em octal e hexadecimal se prefixados corretamente.

A: Você tem que passar o endereço da variável quando usar scanf() e você está esperando um \n no scanf(), no caso não precisa.
Seu código de forma correta ficaria:
#include <stdio.h>
#include <stdlib.h>
int main()
{

        int num1, num2, num3;
        printf("Digite o numero A e numero B para saber o resto da divisao resultante da divisao entre eles:\n");
        printf("NumeroA: "); scanf("%i", &num1);
        printf("\n");
        printf("NumeroB: "); scanf("%i", &num2);
        printf("O resto da divisao e: %i", num1 % num2);
        return 0;
}


text:
Q: JSF / PrimeFaces Validation Hangs JSF/PrimeFaces Validation Problem.
Primefaces validation of inputText fields leaves IE and Firefox browsers in busy cursor mode.
FacesMessage validation message is properly displayed on the page, but busy cursor continues.
Page reload is required to stop the busy cursor.
FireFox Firebug does not indicate a bug.  IE browser indicates a jquery error.
If there is indeed a javascript error, then that would stop all ajax processing.
Phases reported:
START RESTORE_VIEW
END RESTORE_VIEW
START APPLY_REQUEST_VALUES
END APPLY_REQUEST_VALUES
START PROCESS_VALIDATIONS
END PROCESS_VALIDATIONS
START RENDER_RESPONSE
END RENDER_RESPONSE
Has anyone seen this before?


text:
Q: How to set JLabel text to display before a system sleep I'm trying to display the text of Successful Login before a system sleep for 3,000 miliseconds. Its not working when I place it right after the set text. How do I get it to display then pause so there is a bit of delay so the user knows that they loging in?
After the user correctly logs-in it will continue to a different class where the JFrame will close
l_Message.setForeground(Color.green);
l_Message.setText("Succesful Login");

try{
    Thread.sleep(3000);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

PLOGIN post_login = new PLOGIN();
post_login.postlogin_UI(login_JFrame);

A: See Concurrency in Swing for the reason why you're having problems
See How to use Swing Timers for a possible solution
import javax.swing.Timer

//...

l_Message.setForeground(Color.green);
l_Message.setText("Succesful Login");
Timer timer = new Timer(3000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        PLOGIN post_login = new PLOGIN();
        post_login.postlogin_UI(login_JFrame);
    }
});
timer.start();

A: Assuming that you are calling this from outside of the GUI thread(which I believe that you should be), you could try the following:
    EventQueue.invokeLater(() -> {
        l_Message.setForeground(Color.green);
        l_Message.setText("Succesful Login");
    });

    try{
        Thread.sleep(3000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    PLOGIN post_login = new PLOGIN();
    post_login.postlogin_UI(login_JFrame);

i.e. schedule GUI operations to the GUI thread


text:
Q: How does Google create the checkmark for its input checkboxes on the form for creating a new Google account? Scroll to the bottom of the page: https://accounts.google.com/SignUp
The checkbox itself is just CSS - borders, background colors, etc. But I don't see anything in the DOM/CSS that accounts for the actual check mark.

A: Found this css rule in chrome inspect element
input[type="checkbox"]:checked::after {
content: url(//ssl.gstatic.com/ui/v1/menu/checkmark.png);
display: block;
position: absolute;
top: -6px;
left: -5px;
}

Content links to this image
https://ssl.gstatic.com/ui/v1/menu/checkmark.png

A: As Joel put in his answer, it appears the CSS links to a content image.
However, offhand I'd guess it's a non-standard chrome specific thing.  Other browsers don't seem to follow this check content thing very well.  Here's a small sample size:


text:
Q: Save Woocommerce cart item custom data as order item meta data displaying it on orders and emails Regarding Woocommerce. I have custom data that I am adding to the cart. In the functions.php file, I have the following function.
// Display cart item custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_on_cart_and_checkout', 10, 2 );
function display_cart_item_custom_on_cart_and_checkout( $cart_item_data, $cart_item ){

    if( isset($cart_item['custom_data']['label0']) && isset($cart_item['custom_data']['value0']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label0'],
            'value' => $cart_item['custom_data']['value0'],
        );
    }

    if( isset($cart_item['custom_data']['label']) && isset($cart_item['custom_data']['value']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label'],
            'value' => $cart_item['custom_data']['value'],
        );
    }

    if( isset($cart_item['custom_data']['label2']) && isset($cart_item['custom_data']['value2']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label2'],
            'value' => $cart_item['custom_data']['value2'],
        );
    }

    if( isset($cart_item['custom_data']['label3']) && isset($cart_item['custom_data']['value3']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label3'],
            'value' => $cart_item['custom_data']['value3'],
        );
    }

    if( isset($cart_item['custom_data']['label4']) && isset($cart_item['custom_data']['value4']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label4'],
            'value' => $cart_item['custom_data']['value4'],
        );
    }

    if( isset($cart_item['custom_data']['label5']) && isset($cart_item['custom_data']['value5']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label5'],
            'value' => $cart_item['custom_data']['value5'],
        );
    }

    if( isset($cart_item['custom_data']['label6']) && isset($cart_item['custom_data']['value6']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label6'],
            'value' => $cart_item['custom_data']['value6'],
        );
    }

    if( isset($cart_item['custom_data']['label7']) && isset($cart_item['custom_data']['value7']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label7'],
            'value' => $cart_item['custom_data']['value7'],
        );
    }

    if( isset($cart_item['custom_data']['label8']) && isset($cart_item['custom_data']['value8']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label8'],
            'value' => $cart_item['custom_data']['value8'],
        );
    }

    if( isset($cart_item['custom_data']['label9']) && isset($cart_item['custom_data']['value9']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label9'],
            'value' => $cart_item['custom_data']['value9'],
        );
    }

    if( isset($cart_item['custom_data']['label10']) && isset($cart_item['custom_data']['value10']) ) {
        $cart_item_data[] = array(
            'name' => $cart_item['custom_data']['label10'],
            'value' => $cart_item['custom_data']['value10'],
        );
    }
    return $cart_item_data;
}

This works and the custom data is shown in the cart. However, the custom data does not show on the order and order email. I have seen, on Stackoverflow several answers that provide solutions to this problem but I cannot make them work for my situation. The solutions that I reference are.
Save and display order item custom meta data in Woocommerce
Display and save added custom cart item data on Woocommerce Cart, Checkout and Orders
Can anybody kindly show me what "my" function should be?
Thank you.

A: First you can optimize and compact your function this way:
// Display cart item custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_on_cart_and_checkout', 10, 2 );
function display_cart_item_custom_on_cart_and_checkout( $cart_item_data, $cart_item ){
    $keys = array('0','','2','3','4','5','6','7','8','9','10'); // Fields numbers part keys array

    // Loop through Fields numbers part keys array
    foreach( $keys as $key ) {
        if( isset($cart_item['custom_data']['label'.$key]) && isset($cart_item['custom_data']['value'.$key]) ) {
            $cart_item_data[] = array(
                'name' => $cart_item['custom_data']['label'.$key],
                'value' => $cart_item['custom_data']['value'.$key],
            );
        }
    }
    return $cart_item_data;
}

Then to save all your custom cart item data as custom order item meta data and display it everywhere on orders and emails, use the following:
// Save cart item custom data as order item meta data and display it everywhere in Orders and email notifications
add_action('woocommerce_checkout_create_order_line_item', 'save_as_custom_order_item_meta_data', 10, 4 );
function save_as_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {
    $keys = array('0','','2','3','4','5','6','7','8','9','10'); // Fields numbers part keys array()

    // Loop through Fields numbers part keys array
    foreach( $keys as $key ) {
        if( isset( $values['custom_data']['label'.$key] ) && isset( $values['custom_data']['value'.$key] ) ) {
           $item->update_meta_data( $values['custom_data']['label'.$key], $values['custom_data']['value'.$key] );
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should works.


text:
Q: VB.NET Unable to load DLL The specified module could not be found. when dllimport I'm adding VC++ lib in my VB .Net program using for instance:
<DllImport("KMpeg4.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Shared Function KOpenInterface() As System.IntPtr
End Function

I've got at runtime the error:

Unable to load DLL 'KMpeg4.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

I've put this lib everywhere, including system32, still no luck, which mean it missing dependent lib of KMpeg4.dll.
So I've run Dependency walker which gave me the missing lib:

API-MS-WIN-CORE-COM-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL
API-MS-WIN-SHCORE-SCALING-L1-1-0.DLL
DCOMP.DLL
GPSVC.DLL
IESHIMS.DLL

and the bad lnking function:

c:\windows\system32\API-MS-WIN-CORE-THREADPOOL-L1-1-0.DLL
c:\windows\system32\OLE32.DLL
c:\windows\system32\DWMAPI.DLL
c:\windows\system32\IEFRAME.DLL
c:\windows\system32\IMM32.DLL
c:\windows\system32\MFPLAT.DLL
c:\windows\system32\NDFAPI.DLL
c:\windows\system32\USERENV.DLL
c:\windows\system32\UXTHEME.DLL

dependency walker gives the following errors:

Warning: At least one delay-load dependency module was not found.
  Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

I've  I have already install Microsoft VC++ 2005,2008,2010 x86 and x64 and .Net framework 4.
As well I try to see if the KMpeg4.dll popup using sysinternal process monitor, but it does not load KMpeg4.dll befor the program get the error exception
Any ideas from which package those lib could come from?
or alternatively, how to get around this problem?

A: Dependency Walker is not useful to diagnose this problem, DLLs like this are found only at runtime.  Copying into system32 is usually the sledge-hammer solution.  Except on a 64-bit version of Windows with your project's Platform target set to x86, very likely in this case since this is surely a 32-bit DLL, you then need to hammer it into c:\windows\syswow64.
But don't do that, you just need to make sure that the DLL is present in the same directory as your project's EXE.  Best way to do so:

*

*Right-click your EXE project, Add + Existing item

*Navigate to your copy of KMpeg4.dll and select it

*Select the added item, set the Copy to Output Directory property to "Copy if newer"

Rebuild and you'll now have a copy of the DLL in the right place.  Don't forget to deploy it along with your project's executables and don't forget the runtime support DLL that it might need on your user's machine.


text:
Q: hudson incremental maven build always fail, while full maven build succeeds Upon each change commited to our svn, hudson initiates a maven build with the -amd -pl flags, to make only the changed projects. However, the project it compiles "a" is dependent on another project "b", and it fails while looking for "b" in maven repositories across the web. Half an hour later it does a full build and succeeds...
Maybe we've set up our maven dependencies wrong? We have several projects a,b,c and one "maven-parent" project who has only a pom.xml with this in it:
<project>
    <artifactId>maven-parent</artifactId>
    <packaging>pom</packaging>
    <modules>
         <module>../a</module>
         <module>../b</module>
         <module>../c</module>
    </modules>
</project>

and the "a" project references "b" like so:
<project>
    <artifactId>a</artifactId>
    <packaging>jar</packaging>
...
    <dependency>
      <groupId>com.pursway</groupId>
      <artifactId>plummet</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>
</project>

Thanks!

A: Perhaps you should try -am -pl.  From mvn --help
 -am,--also-make                        If project list is specified, also
                                        build projects required by the
                                        list
 -amd,--also-make-dependents            If project list is specified, also
                                        build projects that depend on
                                        projects on the list

A: Set up each project as a separate project in Hudson and use the Hudson configuration for downstream dependant projects to build whatever is necessary depending on the scm changes.

A: You can specify what Raguram has pointed out in hudson project configuration. Under the build
option you can specify Maven Goals and options.
See that in image below
http://imageshack.us/photo/my-images/696/hudsonmaven.jpg/


text:
Q: Why cant i show error message? When username == username from the database and date == date from the database, it should echo an error message but instead it shows success. I tried using "=", but the result keeps echoing the error message even when the data is suppose to be correct. Please help.
These are my codes:
    if(!empty($_POST['username'])){

        $username=$_POST['username'];
        }
        else
        {
        $username=null;
        $usererr = "";
        }

     if(!empty($_POST['datepicker'])){
       $date = date('y-m-d', strtotime($_POST['datepicker']));
       }
        else
        {
        $date=null;
        $dateerr = "";
        }

        $mysqli = new mysqli("", "", "", "");

            $stmt = $mysqli->prepare("SELECT username, date FROM booking WHERE username='$username' and date ='$date'");

            $stmt->bind_param("ss", $username, $date);

            $stmt->execute();

            $stmt->bind_result($cusername, $cdate);
            $stmt->fetch();

        if($cusername == $username && $cdate == $date){
            echo"You have already book this day. Please select another day";
        }
        else{
            echo"Success";
            $chdate = $date;
        }
         if($username && $date && $chdate){

        session_start();

        $mysqli = new mysqli("", "", "", "");

        stmt = $mysqli->prepare("INSERT INTO booking (, , , , )
                            VALUES ('',''");

        $result = $stmt->execute();

        }
        $stmt->close();
        $mysqli->close();

A: check this
$date = date('y-m-d', strtotime($_POST['datepicker']));

this will return year as "17" for 2017, try like this
 $date = date('Y-m-d', strtotime($_POST['datepicker']));


text:
Q: How can I set up this conditional formatting in Excel 2010? We create sections by highlighting an area in Excel 2010 and clicking ALL BORDERS.  We want to set it so that any time you type "REPLA" between columns J and Q, the line that "REPLA" is in will Fill Color to YELLOW, but ONLY the line within the Bordered area (between J and Q).
Also will need two other words that become other colors.

A: You can use this tutorial on conditional formatting to build a solution for your needs:
Automatically Highlight Max Value in a Data Table Using Conditional Formatting
Instead of using the formula:
=$G4=MAX($G:$G)

Replace it with your conditional:
=$G4="REPLA"

Note that the specified range in your case will also be changing to J:Q, etc.


text:
Q: Python - Split tab delimited file and convert to dataframe This is the line I copy and pasted from the file:
UNBILL REC        18041667.97    55851351.64           0.00          0.00           0.00   -57467160.72          33.28     -1615775.80    16425892.17

I believe is tab delimited that I'm using the following code:
with open('file.txt','r') as file_handle:
    example_file_content = file_handle.read().split("\n")
alignmentMatrix = []
for index, line in enumerate(example_file_content):
    if "UNBILL REC" in line:
        print(re.split(r'\t+',line.lstrip()))
        alignmentMatrix.append(re.split(r'\t+',line.lstrip()))
alignmentDF = pd.DataFrame(alignmentMatrix)

The problem is that this gives me a list like:
['UNBILL REC         4166047.25     3498767.15           0.00          0.00           0.00    -3058993.54           0.00       439773.61     4605820.86']

When converted to a dataframe then, all values are put into one column, instead of one value for each column.
My expected output would be:
['UNBILL REC','4166047.25','3498767.15','0.00','0.00','0.00','-3058993.54','0.00','439773.61','4605820.86']

A: You can assign re.split() of alignmentMatrix[0] to a Dataframe:
re.split('\s{2,}',alignmentMatrix[0])

A: Why not read the file as if it was a csv? Then transpose it
df = pandas.read_csv("file.txt", sep="\t")
df_tr = df.transpose()


text:
Q: Function for split digits in list and unique number/code for every digit I have a data input which I want to bring into a specific shape.
Data looks like this:
01211231202143244400222255340042523252102440536423024350201113345340514003134
20023230143300003201455331343005145134541545264403161213336031512541125234215
01203204313112402314341530533423155434004002652564464622316236363153203455225

My code:
with open('Dataday8.in') as file:
    data = [i for i in file.read().split()]

After the code it looks like:
data = ['01211231202143244400222255340042523252102440536423024350201113345340514003', '2002323014330000320145533134300514513454154526440316121333603151254112523421', '0120320431311240231434153053342315543400400265256446462231623636315320345522']

Buy I want it to be seperates after every digit (but each line should be in one bracket). Does not matter what I try my code never brings me to the goal.
After this I would like to give every digit in the list a unique number that I can work with it in a loop.
Thanks for any help
This is the code I tried to split after every digit in the list:
[x for x in data.split('\n')]

A: I am simply reporting Maurice Meyer's answer which perfectly solves the problem for better future readability. Furthermore, if you want to get integers, you simply need to di
data = [list(int(i)) for i in file.read().split()]
data = [[int(elem) for elem in row] for row in data]

A: Although already solved by Sala, i think your problem of int object is not iterable could be solved with this:
data = list([int(elem) for elem in row] for row in (i for i in file.read().split()))

You can also write it like this:
data = list(list(int(elem) for elem in row) for row in (i for i in file.read().split()))

This is a one-liner but of course you can break it down.


text:
Q: How to build third party API's using grape gem and jwt as authentication I have an web app with api's built for android and ios apps. With JWT token for authentication.
Now I want to build third party api's for my app clients to integrate apis into there websites.
I integrated Grape gem, grape-swagger for building api's.
As I'm already using JWT for native app api's. I'm trying to use same authentication for third party apis.
I'm assuming it is safe to use JWT for api's but still I'm asking. Is it safe to use JWT for third party api's because client could expose his token?
I need some references/links on how to building third party apis using jwt as authentication and grape.
How do I proceed with jwt authentication and grape

*

*Shall I give client a page in the website to add custom secret key for encryption then generate token with user.id and email as payload, so that he can validate signature on his end. And ask client to send this token for all future requests.

*Shall I create /users/sign_in api and when user sends username password. Shall I send jwt token with 24 hours expiration and ask client to generate new token for every 24 hours.

Is there any other way I can do authentication

A: I use JWT for authentication using my own scheme using Authorization: header as well as for whole communication between client and server. The Grape::API handler begins with:
content_type    :jwt, 'application/jwt'
formatter       :jwt, Rack::JWTFormatter
parser          :jwt, Rack::JWTParser
format          :jwt

Errors are formatted with error_formatter and if recepient is unknown (i.e. "iss" claim not found), it is returned without signing/encrypting using JWT.encode(data, nil, 'none')
How to implement formatter and parser is described in Grape Documentation.


text:
Q: Netbeans curly braces formatting When i am declaring a new method in netbeans, i do as follows:

$cursor is used to mark the position of the cursor

public void inc(){$cursor}

Then i hit enter, the output is as follows:
public void inc(){
$cursor}

What i want is as follows:
public void inc(){
    $cursor
}

How can achieve this result in netbeans?

A: I do this:
public void inc(){$cursor

then hit enter.
In short: You don't type out the second curly brace, it's generated for you together with an extra line break.


text:
Q: Groovy remove value from collection In groovy is there a specific way to remove a value from a collection. For example I have a list of form fields but two of them are hidden fields and I'm trying to figure out how to remove them from the collection. The two parameters I'm trying to remove are salesKey and topicSelection.  Groovy newbie so code samples are most helpful
request.requestParameterMap.collect { key, value -> "$key: ${value[0].string}" }.join("\n")
key.remove("salesKey")
key.remove("topicSelection")

A: I think you could use findAll:
request.requestParameterMap.findAll { key, value ->
    !( key in ["salesKey", "topicSelection"] )
}

A: Check out this answer.
Also, depending on your specific aims, there are a couple of other ways to remove a pair, including dropWhile (which is more or less iterating over your data struct) and minus (which isn't so much removing a pair as creating a new structure without the specified pair). Official doc here.


text:
Q: chrome opens for a second and crashes using selenium 3, mac OS:10.13.5, chrome: 70, chromedriver: 2.43 I am getting the below error:
For a second, chrome opens and then crashes again
org.openqa.selenium.SessionNotCreatedException:
session not created
from disconnected: unable to connect to renderer
  (Session info: chrome=70.0.3538.67)
  (Driver info: chromedriver=2.43.600229 (3fae4d0cda5334b4f533bede5a4787f7b832d052),platform=Mac OS X 10.13.5 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.02 seconds
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'kewm1584.noths.hq', ip: 'fe80:0:0:0:417:93bd:2501:51d8%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.5', java.version: '1.8.0_181'
Driver info: driver.version: ChromeDriver

what else needs to be done to get this working?


text:
Q: Django sum on an external attribut I have an issue with database and sum in Django.
I have 3 tables: customer, order and orderLine.
For a report, I would like to calculate the sum of all line price for every order of a customer.
class Customer(models.Model):
    firstName = models.CharField(max_length=200)
    lastName = models.CharField(max_length=200)
    mail = models.EmailField(max_length=100)
    etc...

    def get_count_of_orders(self):
        return self.orders.count()

    def get_sum_line_prince_of_all_orders(self):
        ???????????
        return (sum_of_all_line_prince_all_orders)

class Order(models.Model):
    orderNum = models.CharField(max_length=200)
    customer = models.ForeignKey(Customer, related_name="orders")
    globalAmount = models.DecimalField(max_digits=20, decimal_places=4)
    ...

class OrderLine(models.Model):
    order = models.ForeignKey(Order, related_name="ordersLines")
    linePrice = models.DecimalField(max_digits=20, decimal_places=4)
    ...

I don't know what to set in get_sum_of_orders to get the right result.
I've trayed different things like annotate or aggregate.
But without success at the moment.
I didn't understand this process at the moment.
Could you help me?

A: You can access all orders with:
self.orders.all()

and you can iterate them with:
sum = 0
for each_order in self.orders.all():
    sum += each_order.globalAmount
return sum

Here I presume that globalAmount is the amount you need to calculate.
If you need to reach OrderLine -> linePrice through each customer and calculate the sum of the linePrice(s) of each customer, try the following:
for each_order in self.orders.all():  #each order
    for each_OrderLine in each_order.ordersLines.all()
        sum += each_OrderLine.linePrice

Or you could use list comprehension:
sum([myorder.linePrice for myorder in order.ordersLines.all() for order in self.orders.all()])


text:
Q: How to stop Laravel request from getting manipulated using Burp tool? My tester has integrated Burp tool with firefox, where he is running our project on same browser. He is saving each and every request of application in Burp tool and then login with another user to post request data of first user, or he logout of system and only post request data where he is able to save that data properly. Can anybody please answer that how I can stop laravel to save data on Burp or any other tool like this

A: This is an integral part of testing. You should not be trying to find ways to deceive testing tools. You should be implementing good security in your application.


text:
Q: Webpack - warn when import is undefined / not declared Is there a way to get a warning/error message when imports are undefined, i.e. not declared in a file that I am importing from?
// file1.js
export const var1 = 'var1'

// file2.js
import { var2 } from './file1'

var2() // this will throw an error

How to solve this issue?
I am using webpack in version 3.11.0

A: Yes, you can use module.strictExportPresence:

{
  module: {
    strictExportPresence: true
  }
}


text:
Q: DataContract not using Name property specified in attribute I don't know what serializer is being used but I'm seeing some inconsistent behavior during serialization when using the Name property of the datacontract attribute.
Here's an example of what I'm doing:
[XmlRoot(ElementName = "ASerCollection")]
public class SerCollection : List<ColElem>
{
}

[DataContract(Name = "SomethignElse", Namespace = "")]
public class ColElem
{

}

The problem I'm having is that the serialization is generating something like the following XML:
<ASerCollection>
<ColElem />
</ASerCollection>

I'm doing this as part of a WCF Service.  Please let me know if there's something I can do differently to force the use of the "Name" attribute of my datacontract.
Thanks

A: This is because:

*

*XMLRootAttribute is used by XmlSerializer

*DataContractAttribute is used by DataContractSerializer

One does not understand attributes of the other.
Depending on what you are trying to do and the relationships between your classes, I think you should read on how to guide the above mentioned serializers and choose the one that suites the needs.
Here is a couple of links:

*

*http://msdn.microsoft.com/en-us/library/e123c76w.aspx

*http://msdn.microsoft.com/en-us/library/kd1dc9w5.aspx
Hope this helps a bit.


text:
Q: How to add field to upload image by Redux Form? I want to make a submit form by Redux-Form which has a image upload field along with other text fields. I have tried the following approach for image upload and the problem is whenever I try to upload image the form gets re-rendered. How can I do it in a proper way? And another thing is How can I send entire form data (including uploaded image) to Back end? I have used here react,redux-form and material-ui
           <Box className={classes.controlTitle}>
              Upload Organization Logo
            </Box>
            <Field
              name="logo"
              type="file"
              component={renderField}
              placeholder="Upload your organization logo"
              className={classes.field}
            />

A: I suggest using something like react-uploady. It takes care of the file upload for you and you can use any form/components/ui libraries with it:

import React, { useState, useCallback, useMemo, forwardRef } from "react";
import styled, { css } from "styled-components";
import Uploady, {
  useBatchAddListener,
  useBatchFinishListener,
  useUploadyContext
} from "@rpldy/uploady";
import { asUploadButton } from "@rpldy/upload-button";

const MyUploadField = asUploadButton(
  forwardRef(({ onChange, ...props }, ref) => {
    const [text, setText] = useState("Select file");

    useBatchAddListener((batch) => {
      setText(batch.items[0].file.name);
      onChange(batch.items[0].file.name);
    });

    useBatchFinishListener(() => {
      setText("Select file");
      onChange(null);
    });

    return (

        {text}

    );
  })
);

const MyForm = () => {
  const [fields, setFields] = useState({});
  const [fileName, setFileName] = useState(null);
  const uploadyContext = useUploadyContext();

  const onSubmit = useCallback(() => {
    uploadyContext.processPending({ params: fields });
  }, [fields, uploadyContext]);

  const onFieldChange = useCallback(
    (e) => {
      setFields({
        ...fields,
        [e.currentTarget.id]: e.currentTarget.value
      });
    },
    [fields, setFields]
  );

  const buttonExtraProps = useMemo(
    () => ({
      onChange: setFileName
    }),
    [setFileName]
  );

  return (
    <Form>
      <MyUploadField autoUpload={false} extraProps={buttonExtraProps} />

      <input
        onChange={onFieldChange}
        id="field-name"
        type="text"
        placeholder="your name"
      />

      <input
        onChange={onFieldChange}
        id="field-age"
        type="number"
        placeholder="your age"
      />

      <button>
        id="form-submit"
        type="button"
        onClick={onSubmit}
        disabled={!fileName}
      >
        Submit Form
      </button>
    </Form>
  );
};

export default function App() {
  return (

      <Uploady
        clearPendingOnAdd
        destination={{ url: "[upload-url]" }}
        multiple={false}
      >
        <MyForm />
      </Uploady>

  );
}

You can check out this sandbox for a complete example.


text:
Q: Proxy requests from webpack dev server to .net MVC site I would like to integrate Vue in my .net MVC project. I've installed Vue using the CLI and added the following vue.config.js:
module.exports = {
  devServer: {
    proxy: {
      '/': {
        target: 'http://mvcsite.local',
        changeOrigin: true
      }
    },
    disableHostCheck: true
  },
  runtimeCompiler: true
};

The proxy works fine, except that a request to the root http://localhost:8080 (which the dev server runs at) serves the index.html generated by Vue, rather than proxying the request to the root of http://mvcsite.local. How do I proxy that particular request?

A: As indicated in your comment, there is an open issue on github for this, so currently there seems to be no fix. In my case (ASP.NET MVC 4) I solved the problem using a workaround. I simply move the root dir to /Home in development environment. Of course your server backend has to support this scenario, but that's usually the smaller problem. My working vue.config.js for @vue/cli 3 looks like this:
module.exports = {

publicPath: "/Home",

devServer: {
    publicPath: "/Home",
    proxy:
    {
        '^/Home/*': {
            target: 'http://localhost:50353/',
            ws: true,
            changeOrigin: true
        }

    },

}


text:
Q: Problems with SkyScanner Widget in webpage I am following this example to include a SkyScanner widget on my website:
http://business.skyscanner.net/portal/en-GB/Documentation/Widgets
For some reason I just get an empty div - could this be something to do with the key? When I clicked on the activation link I got from SkyScanner for the widget key, I got a page saying the following:

Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be
  viewable on remote machines, please create a  tag within
  a "web.config" configuration file located in the root directory of the
  current web application. This  tag should then have its
  "mode" attribute set to "Off".

I have created a web.config file with the following code:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

I've had a look at 'inspect element' on Chrome and get the error

Uncaught TypeError: Object # has no method 'write'
  api.ashx?key=[KEY]:1

This is the JS:
var API_KEY = 'b7290ac3-1f9f-4575-88a7-89fed0c61f7f',
MAIN_URL = 'http://api.skyscanner.net/api.ashx?key=' + API_KEY;

function main(){
    console.log('loaded module');
    var snippet = new skyscanner.snippets.SearchPanelControl();
    snippet.setCurrency('GBP');
    snippet.setDeparture('uk');
    snippet.draw(document.getElementById('snippet_searchpanel'));
};

function newWrite(str) {
    $(str).appendTo('body');
}

var oldWrite = document.write;
document.write = newWrite;

function onMainSkyscannerScriptLoad(e) {
    console.log('loaded main script');
    skyscanner.loadAndWait('snippets', '1', {'nocss' : true}, main);
}

$('button').click(function() {
                  console.log('getting main script');
                  $.getScript(MAIN_URL, onMainSkyscannerScriptLoad);
                  });

I also used this to personalise the widget:
skyscanner.load("snippets","2");
function main(){
    var snippet = new skyscanner.snippets.SearchPanelControl();
    snippet.setShape("box300x250");
    snippet.setCulture("en-GB");
    snippet.setCurrency("USD");
    snippet.setColourScheme("classicbluelight");
    snippet.setProduct("flights","1");
    snippet.setProduct("hotels","2");
    snippet.setProduct("carhire","3");

    snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);

A: Skyscanner B2B support engineer here. Are you still having trouble with this?
For the quickest response, please contact us here: http://business.skyscanner.net/portal/en-GB/Home/Contact
The first thing to check is that the file is on a web server (localhost is fine), and not loaded from the desktop (or local disk in general). This is because some of the Skyscanner JS code looks up other files using URLs like //api.skyscanner.net. In other words, saving the file to the desktop and opening it from there will not work (will show as an empty div). Here's the most basic example of drawing a widget. Can you try putting this in a file and accessing it through a server? If it works we can build on it :)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


text:
Q: Google cloud datastore only store unique entity I am trying to learn NoSQL with Google Datastore but I am running into a problem with uniqueness.
Consider an ecommerce store, it has categories and products.
You do not want two products of the same SKU in the database.
So I insert an entity with JSON:
{"sku": 1234, "product_name": "Test product"}

And it shows up with two fields. But then I can do that again and I have two or more identical products.
How do you avoid this? Can you make the sku field unique?
Do I need to do a query before insert?
The same issue arises with categories. Should I just use one entity for ALL my categories and stucture it in my JSON?
What is a good common practice here?

A: Create a new kind called 'sku'. When you create a new product, you'll want to do a transactional insert of both the product entity and the sku entity.
For example, let's say you want to add a new product with the kind name product with the id of abc:

*

*"product/abc" = {"sku": 1234, "product_name": "Test product"}
To ensure uniqueness on the property "sku", you'll always want to insert an entity with the kind name sku and the id that equals the property's value:

*

*"sku/1234" = {"created": "2017-05-11"}
The above example entity has a property for created date - just something optional I threw in as part of the example.
Now, as long as you insert both of these as part of the same transaction, you will be ensuring that the "sku" property has a unique value. This works because:

*

*Insert ensures write will fail if the sku entity for that number already exists

*The transaction ensures writing the product entity (with the sku value) and the sku entity are atomic - so if the sku isn't unique, writing the sku entity will fail, causing the product entity write to also fail.

A: You can use "sku" as an "id" (if it's a number) or "name" (if it's a string) for your entity, instead of storing "sku" as a property. Then it's guaranteed to be unique as it becomes part of the unique entity key.

A: Data model is a big subject but IMO there are two approaches you can choose. This is more fundamental rather specific to your question. It gives some ideas.
The first approach – storing a reference as a property
Same as thinking of product contains product variants ...
This approach sort of the same from RDBMS world. You can create products separately, and each product will have a reference in each product variants. It is similar to how foreign keys work in databases. So, you will have a new property for the product variant entities, which will contain a reference to the product to which it belongs. The product attribute will actually contain the key of an entity of the Product Kind.  If it sounds confusing this is how u can dissect it. I will use python as example:
# product model
class Product(ndb.Model):
    name = ndb.StringProperty()

# product variant model
class ProductVariant(ndb.Model):
    name = ndb.StringProperty()
    price = ndb.IntegerProperty()
    # product key.
    product = ndb.KeyProperty(kind=Product)

hugoboss = Product(name="Hugo Boss", key=ndb.Key(Product, 'hugoboss'))
gap = Product(name="Gap", key=ndb.Key(Gap, 'gap'))

pants1 = ProductVariant(name="Black panst", price=300, product=hugoboss.key)
pants2 = ProductVariant(name="Grey pants", price=200, product=hugoboss.key)
tshirt = ProductVariant(name="White graphic tshirt", price=10, product=gap.key)

pants1.put()
pants2.put()
tshirt.put()

# so lets say give me all pants that has label hugoboss
for pants in ProductVariant.query(ProductVariant.product == hugoboss.key).fetch(10):
    print pants.name

# You should get something:
Black pants
Grey panst

The second approach – a product within the key
To take full advantage of it you need to know about sorting feature of Bigtable(Datastore build on top of Bigtable) row keys and how data manipulated around it.  if you want to deep dive there is great paper Bigtable: A Distributed Storage System for Structured Data
# product model
class Product(ndb.Model):
    name = ndb.StringProperty()

# product variant model
class ProductVariant(ndb.Model):
    name = ndb.StringProperty()
    price = ndb.IntegerProperty()

hugoboss = ndb.Key(Product, 'hugoboss')
gap = ndb.Key(Product, 'gap')

Product(name="Hugo Boss", key=hugoboss).put()
Product(name="Gap", key=gap).put()

pants1 = ProductVariant(name="Black pants", price=300, parent=hugoboss)
pants2 = ProductVariant(name="Grey pants", price=200, parent=hugoboss)
tshirt = ProductVariant(name="White graphic tshirt", price=10, parent=gap)

pants1.put()
pants2.put()
tshirt.put()

# so lets say give me all pants that has label hugoboss
for pants in ProductVariant.query(ancestor=hugoboss).fetch(10):
    print pants.name

# You should get something:
Black pants
Grey pants

Second approach is very powerful!  I hope this helps.


text:
Q: Java arrays of multiple parents and children need to find out if all children of a specified parent are deletable So I have the following problem. I have a tree in UI and in DB I have data showing which node has which parented, so I lose the direct connection I have in UI. I need to know if every object is deletable or not based if it's children are.
Data1
name    id    deletable   parentId
A       1     1           0
B1      2     1           1
B2      3     1           1
C1      4     0           3
C2      5     1           3
D1      6     1           5

I get a request to delete a certain ID, I need to verify if I can delete it. The problem is that I don't have a good method of finding if the Childs all are deletable.
Ex: I get request to delete(id = 3) it won't be possible as it's child with id = 4 is not deletable.
I have options to either do this in SQL or in Java. Was thinking of the following
Data1[] obj = getAllData() //it will also get objects which have no direct link to the id we provided
recursiveMethod(obj, id);

recursiveMethod(Data1[] obj, currentParentId) {
     //last node
    if(obj.lenth == 1)
        return obj.getIdDeletable;
    //filter obj for childs having parentId= currentParentId
    childs[] = logic;
    for(Data1 child: childs) {
        recursiveMethod(obj, child.getId)
    }
}

The data U work in backend are arrays and I start with the Id of the object I want to delete. I am stuck on how to find out if it's deletable or not

A: I'm not sure about the methods I have available to get the data needed but I was thinking about something like this:
Edited:
public static void main(String[] args)
{
    int id; // = some id
    Data1[] objs = getAllData(); //it will also get objects which have no direct link to the id we provided
    boolean canDelete = isDeletable(objs[id-1], objs);
}

public static boolean isDeletable(Data1 parent, Data1[] objs)
{
    if(parent.getIdDeletable() == 0)
        return false;

    int pid = parent.getId();
    for(Data1 o: obj)
    {
        if(o.getParentId() == pid && !isDeletable(o, objs))
            return false;
    }
    return true;
}

Steps:

*

*If the parent cannot be deleted return false

*Else check every child

*If there is a child that cannot be deleted return false

*Else return true

Which means that the function returns true is the object and its children can be deleted.


text:
Q: Не отображается сообщение в alert Есть два файла, в первом находится форма и javascript,во втором код php который пересылает данные с первого файла в БД . Я пытаюсь сделать,чтобы при вводе данных  и нажатии  кнопки отправить выводилось сообщение об успешной отправке,иначе об ошибке,но эти сообщения не выводит,хотя данные в ьд добавляются. Помогите пожалуйста.
Файл 1(html)
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Добавление клиента</title>

<form>
клиент

<input type="text" name="klient" />

ОП_форма

<textarea name="op_forma" ></textarea>

<input type="submit"  id="send"  value="Добавить" />
</form>

Файл 2(php)
<?php
$connection=mysql_connect("localhost","reklama","reklama") ;
mysql_select_db('reklama');
mysql_set_charset("SET NAMES utf8");
$ret=true;

mysql_query(" INSERT INTO `klienti` (klient,op_forma)
    VALUES ('". $_POST ['klient'] ."' , '" .  $_POST ['op_forma']  ."')") or $ret=false;
echo $ret;
 ?>

A: У Вас параллельно с ajax'ом идет обычная отправка формы, и страница перезагружается до того, как приходит ответ на ajax. Чтобы не происходил стандартный (не ajax) submit формы:
$("#send").click(function() {
  var dannie = $("form").serialize();
  $.ajax({
    ...
  });
  return false; // !!!
});

Или - по рекомендации @Other :
$("#send").click(function(event) {
  event.preventDefault(); // !!!
  var dannie = $("form").serialize();
  $.ajax({
    ...
  });
});

A еще:
$("form").submit(function(event) {
  event.preventDefault(); // !!!
  var dannie = $("form").serialize();
  $.ajax({
    ...
  });
});


text:
Q: Regexp in lex. Why does flex behave this way Consider a simple integer digit identifying expression like this:
[0-9]+ printf("Integer");

Now if i give 123 as an input it returns Integer, fair enough. Now if I give s123 as the input it prints out sInteger. The unmatched s is being printed by default ECHO that's cool with me. But why is Integer also printed. Shouldn't lex return just s? My input is considered as a whole string right? I mean s123 is considered as a 1 full input?. As soon as s is encountered which does not match [0-9]+ so it should just echo default unmatched value s123 but why sInteger?

A: The string s123 is being matched by the regex [0-9]+. If you want to match strings which consist of only integers, you should try ^[0-9]+$.


text:
Q: Converting json output from twitter search api to an associative array I have the following code that searches for tweets with the hashtag "baseball".
<?php
echo "
Simple Twitter API Test
";

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "*****",
    'oauth_access_token_secret' => "*****",
    'consumer_key' => "****",
    'consumer_secret' => "*****"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=#baseball';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
echo "
";
print_r($string);
echo "
";
?>

The output that i am getting is of the form :
Simple Twitter API Test
Array
(
    [statuses] => Array
        (
            [0] => Array
                (
                    [metadata] => Array
                        (
                            [result_type] => recent
                            [iso_language_code] => en
                        )
                [created_at] => Sun Feb 23 22:06:36 +0000 2014
                [id] => 4.37710107788E+17
                [id_str] => 437710107787657216
                [text] => Good day at practice #springtraining #baseball http://t.co/Zu8zJ6qAeI
                [source] => Instagram
                [truncated] =>
                [in_reply_to_status_id] =>
                [in_reply_to_status_id_str] =>
                [in_reply_to_user_id] =>
                [in_reply_to_user_id_str] =>
                [in_reply_to_screen_name] =>
                [user] => Array
                    (
                        [id] => 75486410
                        [id_str] => 75486410
                        [name] => Jimi Mosher
                        [screen_name] => zortyonroids
                        [location] =>
                        [description] =>
                        [url] =>
                        [entities] => Array
                            (
                                [description] => Array
                                    (
                                        [urls] => Array
                                            (
                                            )

                                    )

                            )

                        [protected] =>
                        [followers_count] => 12
                        [friends_count] => 161
                        [listed_count] => 0
                        [created_at] => Sat Sep 19 05:58:13 +0000 2009
                        [favourites_count] => 6
                        [utc_offset] =>
                        [time_zone] =>
                        [geo_enabled] => 1
                        [verified] =>
                        [statuses_count] => 50
                        [lang] => en
                        [contributors_enabled] =>
                        [is_translator] =>
                        [is_translation_enabled] =>
                        [profile_background_color] => C0DEED
                        [profile_background_image_url] => http://abs.twimg.com/images/themes/theme1/bg.png
                        [profile_background_image_url_https] => https://abs.twimg.com/images/themes/theme1/bg.png
                        [profile_background_tile] =>
                        [profile_image_url] => http://pbs.twimg.com/profile_images/378800000476940795/6c5ab18350233a756b9980dd2a2e84c1_normal.jpeg
                        [profile_image_url_https] => https://pbs.twimg.com/profile_images/378800000476940795/6c5ab18350233a756b9980dd2a2e84c1_normal.jpeg
                        [profile_banner_url] => https://pbs.twimg.com/profile_banners/75486410/1379568136
                        [profile_link_color] => 0084B4
                        [profile_sidebar_border_color] => C0DEED
                        [profile_sidebar_fill_color] => DDEEF6
                        [profile_text_color] => 333333
                        [profile_use_background_image] => 1
                        [default_profile] => 1
                        [default_profile_image] =>
                        [following] =>
                        [follow_request_sent] =>
                        [notifications] =>
                    )

                [geo] =>
                [coordinates] =>
                [place] =>
                [contributors] =>
                [retweet_count] => 0
                [favorite_count] => 0
                [entities] => Array
                    (
                        [hashtags] => Array
                            (
                                [0] => Array
                                    (
                                        [text] => springtraining
                                        [indices] => Array
                                            (
                                                [0] => 21
                                                [1] => 36
                                            )

                                    )

                                [1] => Array
                                    (
                                        [text] => baseball
                                        [indices] => Array
                                            (
                                                [0] => 37
                                                [1] => 46
                                            )

                                    )

                            )

                        [symbols] => Array
                            (
                            )

                        [urls] => Array
                            (
                                [0] => Array
                                    (
                                        [url] => http://t.co/Zu8zJ6qAeI
                                        [expanded_url] => http://instagram.com/p/kxlYF0yvfD/
                                        [display_url] => instagram.com/p/kxlYF0yvfD/
                                        [indices] => Array
                                            (
                                                [0] => 47
                                                [1] => 69
                                            )

                                    )

                            )

                        [user_mentions] => Array
                            (
                            )

                    )

                [favorited] =>
                [retweeted] =>
                [possibly_sensitive] =>
                [lang] => en
            )

I would like to print only the 'text' as well as the 'created at' fields
.
I am unable to decode json into an associative array and print it using the following code:
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
foreach($string as $items)
    {
        echo "Time and Date of Tweet: ".$items['created_at']."
";
        echo "Tweet: ". $items['text']."
";
        echo "Tweeted by: ". $items['user']['name']."
";
        echo "Screen name: ". $items['user']['screen_name']."
";
        echo "Followers: ". $items['user']['followers_count']."
";
        echo "Friends: ". $items['user']['friends_count']."
";
        echo "Listed: ". $items['user']['listed_count']."

";
    }

Please suggest as to what changes should be made to print the associative array.

A: Change the 2nd parameter of json_decode :
json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);

by
json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), true);

A: To decode a json as an associative array you just need to pass true as second parameter
json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), true);

From documentation

assoc
When TRUE, returned objects will be converted into associative arrays.


text:
Q: Inserir ID em Tabela com 13.346 linhas com LOOP Estou precisando atualizar uma tabela com 13 mil linhas. E essa tabela contem um campo chamado "faixa_cep_id" e todos os ids estão 0. Preciso atualizar isso com um loop para não duplicar os campos (EX: 1, 2, 3, 4...). Alguém poderia dar essa ajuda?
DROP TABLE IF EXISTS `pl_joseanmatias_faixa_cep_peso`;
CREATE TABLE `pl_joseanmatias_faixa_cep_peso` (
  `faixa_cep_id` int(11) NOT NULL,
  `title` varchar(150) NOT NULL,
  `weight_min` float NOT NULL,
  `weight_max` float NOT NULL,
  `postcode_min` int(11) NOT NULL,
  `postcode_max` int(11) NOT NULL,
  `cost` float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

A: Para adicionar um atributo novo em sua tabela e definir ele como auto-incremento pode rodar um ALTER TABLE dessa forma :
ALTER TABLE `nome_tabela`
ADD COLUMN `faixa_cep_id` INT(10) NOT NULL AUTO_INCREMENT FIRST;

Exemplo se a coluna já existir :
ALTER TABLE `nome_tabela`
CHANGE COLUMN `faixa_cep_id` `faixa_cep_id` INT(10) NOT NULL AUTO_INCREMENT FIRST;

Atualização :
Crie o índice :
ALTER TABLE `pl_joseanmatias_faixa_cep_peso`
ADD UNIQUE INDEX `faixa_cep_id` (`faixa_cep_id`);

Em seguida dê o alter table criando um atributo auto-increment
ALTER TABLE `pl_joseanmatias_faixa_cep_peso`
CHANGE COLUMN `faixa_cep_id` `faixa_cep_id` INT(10) NOT NULL AUTO_INCREMENT FIRST;

PS: A cada nova linha o própio banco de dados já insere a numeração automaticamente para você. Então não precisa mexer em nenhum INSERT seu.

A: A resposta do Rafael já resolve o seu problema.
Mas caso queira apenas atualizar os dados sem ter que alterar
o tipo da coluna, segue um exemplo:
declare @i int
set @i =0
while @i < 13346
begin
BEGIN TRAN

update  pl_joseanmatias_faixa_cep_peso set faixa_cep_id = SELECT @i + 1
COMMIT TRAN;
set @i =@i + 1
end


text:
Q: need help in preg_match command in php i want to extract only this text loadcap.jpg?pd=9NE7&str1=str
<style type="text/css">
  .ny_captcha p.ny_cap {
    background-image : url('loadcap.jpg?pd=9NE7&str1=str');
    background-size:100px 32px;
   }
</style>

and i am using this code to do this but every time it shows Array only
preg_match("/url\(\'(.*?)\'\)\;/i",$html,$match);

A: $match is filled with the results of search. $match[0] will contain the text that matched the full pattern, $match[1] will have the text that matched the first captured parenthesized subpattern, and so on.
Source (preg_match documentation)


text:
Q: Copy to last row three worksheets same workbook I have a workbook named SHRP Control Compare.xlsx with three tabs. Tab 1 is SHRP, 2 is SharePoint Control and the last tab is Results. When I copy the from SHRP to Results next I need to copy from SharePoint Control to the next available row in the Results tab. I have tried multiple last row methods can't get it to work. if someone can point me the right direction Appreciate it.

A: Sub copypaste()
Dim wb As Workbook, ws As Worksheet, rng As Range, lr As Long
Set wb = Workbooks("SHRP Control Compare Results.xlsx")
Set ws = wb.Sheets("SharePoint Control")
Set rng = ws.Range("A2:J600")
lr = Sheets("Results").Cells(Rows.Count, "B").End(xlUp).Row
rng.Copy Destination:=ws.Range("B" & lr)
Cells(1, 1).Select
End Sub


text:
Q: ASP.NET Web Service + Module + Public variable = thread safe? In my ASP.NET Web Service I've included a module in which their are Public declared variables. Will they be thread-safe? Will they get mixed up upon simultaneous calls?
Those variables are mostly DatsSet, DataTable and SQLDataAdapter..
Partial code of the module:

Imports System.Data.OleDb
Imports System.Diagnostics

Module modCommon

    Public bDoLog As Boolean
    Public sCurrentODBC As String
    Public cn As SqlConnection
    Public Query1ds As DataSet
    Public Query1 As DataTable
    Public Query1adapter As SqlDataAdapter

@scripni
Thanks, as I'm not familiary with your suggestions, I will move everything locally.
Additionally, will the following variables be thread-safe?:

[ToolboxItem(False)]_
Public Class Service1
     Inherits System.Web.Services.WebService

     Dim sName As String
     Dim sCurrentPath As String

     [WebMethod()]_
     Public Function Capture(ByVal sPath As String) As String
          sName = "Joe"
     End Function
End Class

A: If you're using web services than yes, you will have concurency problems when multiple services will try to access the same resource, and SqlConnection is definetly a resource you don't want shared.
You should make sure that you don't have simultaneous calls to the properties (for ex. by wrapping the fields with getters / setters and implementing locks in those methods) or by moving the code to a class and instantiating that class whenever you need it.


text:
Q: How does the Linux file system/organization differ from Windows? One of the things that really slows me down in catching on with Linux is the huge difference between the file system in Linux versus Windows.  Up until the last 3-4 years I only used Windows systems and its only been the last 2-3 months that I've really worked at getting accustomed to Linux.  I think one of the things that really bothers me at this point is that I felt like I could find just about anything I wanted to when I began digging through the various folders in Windows.  I had become accustomed to what kinds of things were placed where and when.  I don't have that with Linux.  I'm learning a few things like the /opt folder is where most third-party programs get installed... but my understanding is limited.  What things are important to know to really understand the file system and to be able to locate different files and programs and such?

A: In Windows when you install a program, it creates a folder in Program Files that contains everything.  It has the binaries, the libraries, the resource files, etc.  In Linux, binaries usually go in /usr/bin, libraries go in /usr/lib, and resources go in /usr/share.  Specifically with like an icon file, that would go in /usr/share/icons.  Fonts can be found in /usr/share/fonts.  Development headers go in /usr/include, and lastly, configuration files go in /etc.
This layout has some cool advantages.  By putting libraries into /usr/lib, it's much  easier to share libraries between applications.  In Windows, it's typical to see each program install their own set of libraries into Program Files, and another app may install the same exact library so now you have two exact copies of a .dll file.  It also add some consistency to the filesystem layout.  In Windows, you know the program will have a folder in Program Files, but there's no guarantee on how it's layed out inside that folder.  Maybe the executables will be in a bin/ folder, maybe not.  Maybe it will have a conf/ folder, again maybe not.

A: Have a look at the Filesystem Hierarchy Standard (FHS), which is a standard of organising directory structure. I strongly suspect most (all?) Linux-based systems more or less follow it.

A: In some *nix distributions (tested on OpenBSD and Ubuntu) the man page for the file system hierarchy can be useful.
$ man hier

Of course, this will vary depending on platform and how up to date the manual pages are.  The man page (on Ubuntu) also references the Filesystem Hierarchy Standard that was pointed to earlier.
I did not find a similar manual entry on solaris.
In general, different linux distributions are free to put things wherever they want to, so it can get confusing quickly.  Most executables that the system installs (either as part of the base system or through a package manager) will end up somewhere in your default path (usually in /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin) though some distributions use /opt, /usr/share/bin, among others. A parallel could be drawn to the "Program Files" folder in windows. The "Windows" folder could be somewhat like /usr/lib /usr/include /usr/share and others.  Your "My Documents" folder is somewhat parallel to your home directory on linux (/home/user) with the nice addition that most user specific configurations for programs like firefox, thunderbird, etc live here making moving to a new system fairly painless.
The problem with these parallels is they are not exactly accurate.  Windows and linux are different in this respect.
The best way forward is to continue poking around with the system, as you probably did when you first started using windows, break things, fix them, ask questions along the way.


text:
Q: Could a button or tab be added to improve the access to tag synonym voting? To access list of tag synonyms, one has to click this link.
Would it be possible to add a button with this link here (maybe next to the popular tab?):

A: The tag synonym link is available on the above page.  It's in the lower left-hand corner:

You just have to know where to look.  It would be nice if this were more visible.


text:
Q: How to investigate cause of EMC Pre-compliance failure? I'm currently designing a new metal detector product and took it for pre-compliance as I've finished the hardware design and am currently finishing up on the software. I've never developed a product before (previously I've only contributed to prototype designs) so I'm not 100% clear on how to fault find in case of EMC failure. Specifically the test that my product failed was on:
Radiated Field Immunity (EN 61326-1:2013 / EN 61000-4-3:2006).
My product is in a stainless steel enclosure with a diagonal 4.3" (approx 110 mm) rectangular cut out for an LCD display, two 22mm hole cut outs for buttons. Coming out from the bottom of the enclosure is 2x 5m coax cables to connect a transmit and receive coil and 1.8m mains power cable.
Initially during this test, the device failed at all frequencies betwen 470MHz to 520MHz. I then changed the 1.8m mains power cable to a same length shielded cable and also connected this shielded cable to the enclosure. This reduced the number of failures to just specifically those two frequencies (rather than the whole range between). Knowing that the device fails at these two particular frequencies, and knowing that adding a shielded mains power cable greatly improved the pass rate, what information do I have here in order to investigate further? I feel like adding more shielding is a band-aid approach and would like to remove the shielded mains cable completely if I can determine and fix the root cause. Any help or suggestions would be great and I can supply further information if needed.
The page report:

A: First of all, note that some industrial applications might actually require 100V/m susceptibility (such as land-moving machinery, stone crushers, drilling rigs etc).
I also find it weird that general EMC standards are used on what's clearly a RF product. You should probably be using some EN/ETSI ones to test the intentional radiation as well as the unintentional. How about:
ETSI EN 303 454 "Short Range Devices (SRD); Metal and object detection sensors in the frequency range 1 kHz to 148,5 kHz;". Sounds good to me, though your test house should know these things.
So your pre-compliance test is using relatively very low requirements with 10V/m susceptibility and in a reasonably small frequency range. So if you fail the EMC test even with such lax requirements, I would suspect that you have some severe problems in your product beyond shielding/encapsulation.
PCB layout, power electronics layout and grounding would all be the usual culprits to investigate. In case of switching buck regulators, investigate if the frequency might have something in common with the problematic frequencies. Or just provide more details about the supply electronics in a separate question and some power guru could do a design review (layouts have to be done very carefully).
Though my general experience of EMC testing is to not stare blindly at which specific frequencies you were having problems, since it's fairly complex to translate those (and harmonics) to something corresponding to your product.
Also if you have problems with susceptibility you might have problems with emissions too. Particularly in case of RF products as is the case here.
Regarding the encapsulation:

My product is in a stainless steel enclosure with a diagonal 4.3" (approx 110 mm) rectangular cut out for an LCD display, two 22mm hole cut outs for buttons

You will need a conductive EMC gasket around the opening and around the enclosure lid as well. The LCD would ideally be covered in some screening material, since LCDs are quite often the culprit in failing EMC.
Connectors should ideally be metallic/conducting or otherwise you may need to add additional filtering. For tougher EMC requirements you'd typically have "pi" filters on all I/O signals.
Connect your power ground to chassis near where it enters the enclosure.
Shielded cables are "band aid" indeed, as are ferrites on them etc. You should address the root cause, noting that all cables may act as antennas.

A: Sounds like your cable is acting as a receiving antenna for field energy that ends up being conducted into your product as common mode noise. That's a common scenario for RF immunity failures in the hundreds of MHz range as these frequencies have wave lengths in the meter range. That's also a typical length for cables, thus acting as antennas at these frequencies.
Typical fixes often times include common mode filtering of all signals entering your device. That might include ferrites around external and/or internal cables and/or common mode filtering directly on your PCB.
Sometimes it's sufficient to apply common mode filtering to the inputs of high gain amplifiers only, for example. Because high gain amplifiers might have a tendency to rectify and amplify common mode RF noise.
Observing the 1 kHz AM frequency and/or a DC offset at any point of your signal chain is very likely caused by such rectifying effects.


text:
Q: LXDE - Menu icon and panel icon are different, how to fix? Using 64 bit Ubuntu 18.04.3 with LXDE desktop and Numix Circle icons.
Certain applications appear to be using two different sets of icons.  An example is google-earth-pro. This screenshot shows the the icon that appears in the menu (green box) and the icon that appears in the panel for the running application (red box).  The panel icon also appears in the header bar of the application's window.

How does one determine which icon is being used for these two different purposes?  My goal is to make the icons consistent.
Edit per comment:
Some of the other affected applications

*

*NVIDIA X server settings

*

*Audacity


text:
Q: The method setMode("showFrame", true) of axWindowsMediaPlayer not work in WMP 12 for Windows 7 I use axWindowsMediaPlayer control to play video and I use the following method in order to display the current video frame by moving the seek.
axWindowsMediaPlayer1.settings.setMode("showFrame", true);
This function works fine for Windows XP but when I try to execute my desktop application on Windows 7, not work.
Can you help me please?

A: I resolved this problem by programming PositionChange event of the axWindowsMEdiaPlayer component with the following instructions:
        this.axWindowsMediaPlayer1.Ctlcontrols.play();
        this.axWindowsMediaPlayer1.Ctlcontrols.pause();