text:
Q: At what point do I lose the repair penalty I can craft Tools to be at 105. However, when I repair them, I end up with a tool with quality level 100. If I repair again, it goes down further.
How does this work and how much does the respective skill need in comparison to the manufacturing skill in order to get rid of the repair penalty? How close to each other do they have to be, numbers wise?

A: After doing some experimentation, I've come to the conclusion that repairing any tools that you make (not counting higher-quality items that are found) is not worth it at all. The Iron Pickaxe, for example:
One scrap iron = 5 iron in the forge
One forged iron = 10 iron in the forge = 2 scrap iron
Iron Pickaxe = 5 forged iron = 10 scrap iron
Repairing an Iron Pickaxe = 2 forged iron = 4 scrap iron (lost quality)
Scrapping an Iron Pickaxe = 7 scrap iron (3.5 forged iron returned to you)

So basically if you scrap a completely broken pickaxe (because tools crafted with forged iron don't "poof" like stone tools when they get to 0 durability) you get 70% of your original material back. You only need 3 additional scrap iron to craft an item of the same (or higher, if your skill has increased since) quality.
This is also offset by the fact that crafting tools increases your tool construction skill (not necessarily a whole point, depending on your current skill) which will inevitably cause you to create better tools.
As mentioned before, the only exception to this for me is if I find a tool (Iron Pickaxe for example) that is far better quality than I can currently produce. I will repair that item when necessary (only after it's unusable) until it gets down to the level where I can craft a better quality tool, then I scrap it. Because of this, I always keep tools that I find that are higher quality than what I can make.
A side note, the "Quality Joe" (I think it's called) is the first thing I purchase once my Scavenging gets to the required level. It will cause found items to be 25/50/100 points higher quality. Now at around level 40, with Quality Joe maxxed out, I consistently find 600 level clothing and tools and other items, which is a great thing.
Edit: Repairing items may increase your construction tools skill as well, but since I hardly do it, it's not obvious to me. Someone else might chime and and report their findings.
Edit 2: I wanted to also point out that with the advent of getting iron from mining all stone, this produces a practically limitless amount of iron. It only takes a few hits to get 3 iron fragments, which is enough to make up the difference between repairing a pickaxe and creating a new one.
I have yet, however, to determine how this relates to a Steel Pickaxe. Taking 5 Forged Steel (which costs twice as much as Forged Iron) to create, but an unknown amount returned when the item is scrapped. Once I find this out (when it wears down to 0) I'll update again. Due to the speed, I have no reason to use an Iron Pickaxe any longer.
Update (Edit 3): A steel pickaxe will return 15 scrap iron when scrapped, and costs 20 scrap iron to make (again 75%). It requires 5 forged steel to produce, each of which requires 20 "forge iron". So thats 100 "forge iron" (not Forged Iron) which requires 20 scrap metal in total. It's still worth scrapping and building a better one than repairing it, because for me, my tool smithing skill goes up all the time for other things, and I'd rather spend the 5 additional scrap iron and build a better one that mines faster. For example, the first Steel Pickaxe I made was quality 263. By the time that ran out (granted I wasn't mining constantly), my skill increased enough so that my 2nd one was quality 419. Huge difference.

A: I think the current definitive answer to this is you don't lose the repair penalty.
I've been researching this as well, and there is no information on the Wiki or any other source that would indicate that the repair penalty will be 0 at any point.
According to this discussion thread on the steam community, apparently you can modify the xml file which will remove the repair penalty. Now, how/where to do this is not explained.
I think the repair penalty is invoking a real world survival technique. It will eventually just break over time, regardless of how many repairs you to do it.
For information on how much durability is restored with a specific repair item you can visit this wiki page.
I honestly don't think the wiki is up to day with the current alpha release of the game. Unfortunately they do not have the formulas posted yet on how the repairs work.
You can see the formulas on how much durability is removed from an item on this page. This tells me that they may include the calculations for repairing items eventually.


text:
Q: How to do no indentation on next paragraph? (`\noindent` only work on this paragraph) I want to create a macro for section type that starts with a date. I have gotten this far:
\documentclass[a5paper, 11pt]{memoir}
\usepackage{ebgaramond}
\usepackage{lipsum}

\setsecheadstyle{\Large\scshape\memRTLraggedright}

\newcommand{\dateSection}[2]{\section*{#1}{\vspace{-1\baselineskip}\hfill \small #2}\noindent}

\begin{document}
\dateSection{Lorem ipsum}{Monday Mars 21}

\lipsum[1-2]
\end{document}

but I get an indentation after it and the \noindent I have added does not help me.

What can I do to fix this in the macro?

A: Set up the next paragraph to gobble the indentation box.
\documentclass[a5paper, 11pt]{memoir}
\usepackage{ebgaramond}
\usepackage{lipsum}

\setsecheadstyle{\Large\scshape\memRTLraggedright}

\makeatletter
\newcommand{\dateSection}[2]{%
  \section*{#1}%
  {\vspace{-1\baselineskip}\hfill \small #2\par\nobreak}%
  \@afterindentfalse % don't indent the next paragraph
  \@afterheading % don't break pages too early
}
\makeatother

\begin{document}

\dateSection{Lorem ipsum}{Monday Mars 21}

\lipsum[1-2]

\end{document}

This way it's irrelevant whether you have a blank line or not after the \dateSection command.
There will be at least two lines of the next paragraph together with the section title and the date.

A: Adding a \raisebox in your macro definition:
\documentclass[a5paper, 11pt]{memoir}
\usepackage{ebgaramond}
\usepackage{lipsum}

\setsecheadstyle{\Large\scshape\memRTLraggedright}

\newcommand{\dateSection}[2]{\section*{#1\hfill\raisebox{-0.6\baselineskip}[0pt][0pt]{\upshape\small#2}}}

\begin{document}

\dateSection{Lorem ipsum}{Monday Mars 21}

\lipsum[1-2]

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting exception on SQLite create Table I have getting exception when hitting line:  database.CreateTableAsync().Wait();
Exception: System.AggregateException: One or more errors occurred.

A: Yes I have resolved its issue with SQLiteAsyncConnection


text:
Q: Constrained Analysis of Principal Coordinates I used a Constrained Analysis of Principal Coordinates (CAP) to evaluated if my independent variables could explain the ordination of assemblage composition based on species abundances. However, the output only gave me the proportion explained (60.5%) and the F (2.3023) and P (0.003) values for the whole model. But I don't know how to get the deviance explained by each variable and its p-value. I hope someone can help me.
vare.cap <- capscale(ponds ~ PD + PS + COV100 + COV500,
                      dist="bray")
vare.cap
summary(vare.cap)
anova(vare.cap)
anova(vare.cap, by = "axis")

Results:
Partitioning of squared Bray distance:
              Inertia Proportion
Total           2.714     1.0000
Constrained     1.643     0.6055
Unconstrained   1.071     0.3945

 Df          Variance   F    Pr(>F)
Model     4   1.6435 2.3023  0.003 **
Residual  6   1.0708

A: If the variance explained is OK, then this is given by anova(model, by = "margin"). This tests marginal effects, hence this is a test of the amount of additional variance explained by adding that variable to a model that already contains all the other variables.
library("vegan")
data(varespec, varechem)
vare.cap <- capscale(varespec ~ N + P + K + Condition(Al), data = varechem,
                     dist="bray")

anova(vare.cap, by = "margin")

This gives us:
> anova(vare.cap, by = "margin")
Permutation test for capscale under reduced model
Marginal effects of terms
Permutation: free
Number of permutations: 999

Model: capscale(formula = varespec ~ N + P + K + Condition(Al), data = varechem, distance = "bray")
         Df Variance      F Pr(>F)
N         1  0.27719 1.8616  0.093 .
P         1  0.20764 1.3945  0.191
K         1  0.22249 1.4943  0.151
Residual 19  2.82904
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

If you want the marginal variance explained, then you need to divide those values by with(vare.cap, tot.chi - CA$imaginary.chi) if you have imaginary eigenvalues or vby with(vare.cap, tot.chi) if you don't. For example
> set.seed(1)
> marg <- anova(vare.cap, by = "margin")
> marg
Permutation test for capscale under reduced model
Marginal effects of terms
Permutation: free
Number of permutations: 999

Model: capscale(formula = varespec ~ N + P + K + Condition(Al), data = varechem, distance = "bray")
         Df Variance      F Pr(>F)
N         1  0.27719 1.8616  0.065 .
P         1  0.20764 1.3945  0.201
K         1  0.22249 1.4943  0.150
Residual 19  2.82904
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> marg$Variance / with(vare.cap, tot.chi - CA$imaginary.chi)
[1] 0.05770665 0.04322702 0.04631963 0.58896598

That last line contains the proportions of variance explained out of the total variance. If you want to ignore (or don't have any) imaginary eigenvalues, then you can just do
> marg$Variance / with(vare.cap, tot.chi)
[1] 0.06099498 0.04569025 0.04895909 0.62252739


text:
Q: ddslike get two values from diffrentes select i have little problem with ddslike jquery lib
I have two select box like this:
<select id="from">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>

<select id="to">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>

Javascript of SELECT BOX (Want just the design from ddslike):
<script type="text/javascript">
$(document).ready(function () {

$('#from_fees').ddslick({
    width: 100,
});

$('#to_fees').ddslick({
    width: 100,
});
});
</script>

Here my script that i wanted to fetch value of select's options:
  $(function(){
          $("#from").change(function(event){
            //alert("Click event on Select has occurred!");
            $("option:selected", $(this)).each(function(){
                var obj = document.getElementById('from').value;
                alert("selected value"+obj);

            });
          });
        });

But i get no results !
I want get the two value from the two select in the same time.
Thank you.

A: First, you've got to be consistent with your IDs.  You've got id="from" in the html, but you call .ddslick() on the element with id "from_fees".
If I understand, you'd like to get the values of each whenever either one changes.  How about:
<script>
  $('select').change(function(){
    var to = $('#to').val();
    var from = $('#from').val();
    // alert("To: " + to + " and from: " + from + ".");
  });
</script>

You don't need to use "this", because you want the value out of both of them.


text:
Q: Python how to proof a boolean expression in a loop and cancel loop when button clicked Hello i have a Python program with a function "startAutomation" and inside this funtion i have the loop:
for i,j in zip(int_datadelta, int_timedelta):
  Att1.SetAttenuation(i) # Set attenuation
  print('Set Attenuation: ',i)
  lcd.display(i)
  time.sleep(j)

I have 4 buttons "Start", "Stop","Pause" and "Continue". I am able to start the function "startAutomation" with the button "Start" but the other buttons i can't get working. I need something to check the loop (boolean) and if "Stop" is clicked the loop should stop; when "Pause" is clicked the loop should pause as long as the button "Continue" is clicked or aborted when "Stop" is clicked.
This is my code so far:
# start button
def startAutomation(self, lcd, browse_le, rssi_le, add_le, *btns):
  int_timedelta =[]
  int_datadelta =[]
    for i,j in zip(int_datadelta, int_timedelta):
      Att1.SetAttenuation(i) # Set attenuation
      print('Set Attenuation: ',i)
      lcd.display(i)
      time.sleep(j)

def parsed():
  btn3 = QtWidgets.QPushButton('Start')
  btn4 = QtWidgets.QPushButton('Stop')
  btn10 = QtWidgets.QPushButton('Pause')
  btn11 = QtWidgets.QPushButton('Continue')
  btn3.clicked.connect(functools.partial(self.startAutomation, lcd, le, le4, le5, rbtn, rbtn2, rbtn3))
  btn4.clicked.connect(functools.partial(self.stopAutomation))
  btn10.clicked.connect(functools.partial(self.pauseAutomation))
  btn11.clicked.connect(functools.partial(self.continueAutomation))
  hbox3.addWidget(btn3)
  hbox3.addWidget(btn4)
  hbox3.addWidget(btn10)
  hbox3.addWidget(btn11)
  ...
  return vbox

# stop button
def stopAutomation(self):
    print ("Stop")

# pause button
def pauseAutomation(self):
  print ("Pause")

# continue button
def continueAutomation(self):
    print ("Continue")

I tried several things whith a while loop but i can't get it working. It would be glad if someone could help ?

A: You may create a function that sets and returns a variable contains a string of the last pressed button and make actions upon the value of the variable .
def lastPressed(self, what, last_pressed):
    if what == 'set':
        self.last_pressed = last_pressed
    elif what == 'get':
        return self.last_pressed
# start button
def startAutomation(self, lcd, browse_le, rssi_le, add_le, *btns):
    self.lastPressed('set', "Start")
    int_timedelta =[]
    int_datadelta =[]
        for i,j in zip(int_datadelta, int_timedelta):
            last_pressed = self.lastPressed('get', None)
            if  last_pressed == 'Start':
                Att1.SetAttenuation(i) # Set attenuation
                print('Set Attenuation: ',i)
                lcd.display(i)
                time.sleep(j)
            elif  last_pressed == 'Stop':
                ...
            elif  last_pressed == 'Pause':
                ...
            elif  last_pressed == 'Continue':
                ...
def parsed():
    btn3 = QtWidgets.QPushButton('Start')
    btn4 = QtWidgets.QPushButton('Stop')
    btn10 = QtWidgets.QPushButton('Pause')
    btn11 = QtWidgets.QPushButton('Continue')
    btn3.clicked.connect(functools.partial(self.startAutomation, lcd, le, le4, le5, rbtn, rbtn2, rbtn3))
    btn4.clicked.connect(functools.partial(self.stopAutomation))
    btn10.clicked.connect(functools.partial(self.pauseAutomation))
    btn11.clicked.connect(functools.partial(self.continueAutomation))
    hbox3.addWidget(btn3)
    hbox3.addWidget(btn4)
    hbox3.addWidget(btn10)
    hbox3.addWidget(btn11)
    ...
    return vbox
# stop button
def stopAutomation(self):
    self.lastPressed ('set', "Stop")

# pause button
def pauseAutomation(self):
    self.lastPressed ('set', "Pause")

# continue button
def continueAutomation(self):
    self.last_pressed ('set', "Continue")


text:
Q: How to show specific array in foreach <?php

$XMLContent=file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

foreach($XMLContent as $line){
        if(preg_match("/rate='([[:graph:]]+)'/",$line,$rate)){
            echo "$rate[1]
";
        }
 }
?>

but the result are displayed all,my question that displaying data in the first row

A: Use break to stop the loop after the first match:
foreach($XMLContent as $line){
    if(preg_match("/rate='([[:graph:]]+)'/",$line,$rate)){
        echo "$rate[1]
";
        break;
    }
}


text:
Q: Accessing array/set of objects with keys I want to be able to add objects to an NSArray and access them with Keys. Currently the way im doing it is creating a seperate NSDictionary of key-value pairs where the value is an integer number representing the index in my NSArray. This seems like an extra step to me.
If my understanding of NSDictionary is correct, only 'values' can be stored: a pointer to an object cannot.
Surely there must be an equivalent NSDictionary type function that allows objects to be stored and accessed with a key? I have looked through the documentation, but cant seem to find any answers, unless im missing something obvious.

A: NSDictionary is to store key value pairs. if you are adding key value pair after you created the dictioanry, use NSMutableDictionary class . example,
[dictionaryObject setObject:@"" forKey:@"abc"];

A: You can store objects in NSDictionary and can be accessed via keys...

A: In short, no.
An array (NSArray) is an ordered collection of references to objects, so simply said, an ordered collection of objects.
As opposed to dictionaries, which are unordered and values are accessed by keys.
You understanding of collections is probably wrong, you don't store values, but pointers (references).
The extra step is necessary if you need to store the references in an array, but in this case, you should consider using a dictionary. An option is to use keys that take care of the order.
For example :
[myDictionary objectForKey:@"1"];

could be an equivalent of :
[myArray objectAtIndex:1];

A: Thats wrong, you can store objects in a NSDictionary. Look at the method dictionaryWithObjects:forKeys: or dictionaryWithObjectsAndKeys:

A: I have no experience in Cocoa but looking at the documentation it seems like NSDictionary (or at least NSMutableDictionary) should handle your request (without you using NSArray).

A: I think I understand your problem. My suggestion for you is to use NSMutableArray and macros, like:
NSMutableArray *array=[[NSMutableArray alloc]init];
#define SOME_MACRO 0
    id someObject;
    [array insertObject:someObject atIndex:SOME_MACRO];
    id getterObject=[array objectAtIndex:SOME_MACRO];

Of course define the macros in the header file.


text:
Q: Set variables to client socket I'm making a Java TCP Server and a noob question that I can't revolve came to me, what's the way to set variables to the current client socket? Check class Handler, code above may be not important.
import java.io.*;
import java.net.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Handler;

public class tcp_server {
  public static void main(String[] args) {
    int count = 0;

    ExecutorService executor = Executors.newFixedThreadPool(30);
    Socket client;

    try {
      ServerSocket server = new ServerSocket(8080);

      while(true) {
        client = server.accept();
        executor.execute(new Handler(client));
      }
    }
    catch(Exception e) {
      System.out.println(e);
    }
  }

  public static class Handler implements Runnable {
    private Socket client;

    public Handler(Socket client) {
      this.client = client;
    }

    public void run() {
      try {
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
        String event = inFromClient.readLine();
        System.out.println(event);

        // Arrays.copyOfRange(byte[] original, int from, int to)

        // Index
        if(event.equals("GET / HTTP/1.1")) {
          // ...
          client.close();
        }

        // Authenticate
        if(event.charAt(0) == '0') {
          String client_token = Arrays.copyOfRange(byte[] event, int 1, 33);

          // I'm gonna add the MySQL Queries later

          // if session id found on table
          String client_google = "000000000000000000000"; // MySQL
          client.session = client_token; // -> Token received from client. (?)
          client.gid = client_google; // -> Google+ Profile (?)
          // **How do I set variables to the current client?**
        }

        // Sync settings
        if(event.charAt(0) == '0') {
          // ...
          // access non static variable from here
          System.out.println(client.session); // (?)
          System.out.println(client.gid); // (?)
        }

        // More events
      }
      catch(Exception e) {
        System.out.println(e);
      }
    }
  }

  // End.
}

Thanks.

A: There are a few ways to store your data local to your particular connection.
In your example the easiest way would be to declare a session-variable which is a field of Handler, something like:
public static class Handler implements Runnable {
    private Socket client;
    private UserSession session;

    public Handler(Socket client) {
      this.client = client;
      this.session = new UserSession();
    }
 ...

The UserSession can contain what you want. Another option is that UserSession class is exchanged for Map<String, Object>, which will hold key-value mappings local to this user connection. Minuses: if your system grows, you will have to pass the reference to this session to all the methods, which need the session data.
As long as you are using blocking IO for your data input, you can also use such a class as ThreadLocal, which goes out of the box with java. This mechanism does the same as your local variable UserSession, your session variable will be accessible in any part of your code as long as it is run by 1 thread (which is the fact for blocking IO). You can read about it here:
http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html
The last way - a non-blocking thread-pool HTTP way - send a session identifier with every request, sth like user=login. Next, store a large Map<String, UserSession> in the app context (it can be your own singleton, accessible for all threads when reading incoming data), and then retrieve the required session by request parameter (user).


text:
Q: Reading FormData from HttpContext in .Net Core 2.0 In Core 2.0, trying to read in my FormData posted from front end. I can manage to read the array of JSON objects, but not the Files[] array I'm also posting in the Form Data.
Here's the Angular component code which builds FormData :

const formData = new FormData();
formData.append("MediaInfo",  JSON.stringify(minfo));

for(var i=0; i<this.importImages.length; i++){
    // append images to the files[] array
    formData.append("files[]", this.dataURItoBlob(this.importImages[i].TnUrl), this.importImages[i].name);
   }

And I call the following Angular service:

 saveImportObjects(formData: FormData, params){
  let headers = new Headers();
  let options = new RequestOptions({ headers: headers });
  options.params = params;

  var url = this.host + 'import/MediaUpload?' + this.getSessionID();

  return this.http.post(url, formData, options)
          .map((result: any) => {
            let res = result._body;
          })
          .catch(this.handleError);
}

The Web Api code :

[HttpPost]
[Route("MediaUpload")]
[DisableFormValueModelBindingAttribute]
public async Task<HttpResponseMessage> MediaUploadAsync(string patientId, [FromQuery]string sessionId)
{

 FormOptions _defaultFormOptions = new FormOptions();

 if (!Helpers.MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
 {
  throw new GetDataException("Unsupported Media Type");
 }

 var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
 var reader = new MultipartReader(boundary, HttpContext.Request.Body);
 var section = await reader.ReadNextSectionAsync();

 StreamReader stream = new StreamReader(section.Body, Encoding.UTF8);
 var data = stream.ReadToEndAsync();

  List<MediaInfo> listMedia = new List<MediaInfo>();

 HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.Accepted);
 return msg;
}

The good news is that my data object is showing the array of objects (one object in this case); however, I'm not getting to my Files[] array:

[{"PatientID":2,"PatientLastName":"Comprehensive","PatientFirstName":"Connie","DeviceID":"46","CSIInstanceID":9,"PatientDOB":"1958-09-09","FileName":"eye2.jpg","FileSize":5880,"ExamDate":"1/29/2018","PatientUID":2,"SessionID":"sessionID=4e92cdc3-3cba-4c96-86fa-d8049d9ea968"}]

Captured request in Fiddler tool:

POST /api/import/MediaUpload?sessionID=cfe351c8-63f8-40b0-909d-d9a5991f6a70&patientID=11 HTTP/1.1

POST /api/import/MediaUpload?sessionID=cfe351c8-63f8-40b0-909d-d9a5991f6a70&patientID=11 HTTP/1.1
Host: localhost:49491
Connection: keep-alive
Content-Length: 399616
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary62hryFjhCKbptVPz
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

Same request via Fiddler, in the TextView of request:

------WebKitFormBoundary62hryFjhCKbptVPz
Content-Disposition: form-data; name="MediaInfo"

[{"ID":11,"LastName":"Mazzo","FirstName":"Bob","DeviceID":"46","InstanceID":9,"PatientDOB":"1967-05-01","FileName":"Bob and Chris Cardillo.jpg","FileSize":399030,"ExamDate":"1/31/2018","UID":11,"SessionID":"sessionID=cfe351c8-63f8-40b0-909d-d9a5991f6a70"}]
------WebKitFormBoundary62hryFjhCKbptVPz
Content-Disposition: form-data; name="files[]"; filename="Bob and Chris Cardillo.jpg"
Content-Type: image/jpeg

A: This code working. I can now read in the "MediaInfo"object, as well as the "files[]" array.

[HttpPost]
[Route("MediaUpload")]
[DisableFormValueModelBindingAttribute]
public async Task<HttpResponseMessage> MediaUploadAsync(string Id, [FromQuery]string sessionId)
{
 AppSettings config = new AppSettings();
 var importConfig = config.GetImportConfig();
 var localPath = importConfig["ImportImageFolderPath"];

 FormOptions _defaultFormOptions = new FormOptions();
 List<MediaInfo> listMedia = new List<MediaInfo>();

 if (!Helpers.MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
 {
  throw new GetDataException("Unsupported Media Type");
 }

 var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
 var reader = new MultipartReader(boundary, HttpContext.Request.Body);

 var section = await reader.ReadNextSectionAsync();
 StreamReader stream = new StreamReader(section.Body, Encoding.UTF8);

 // READ FORM DATA
 if (section.ContentDisposition.Contains("MediaInfo"))
 {
  var data = stream.ReadLine();
  listMedia = JsonConvert.DeserializeObject<List<MediaInfo>>(data);
 }

 CreateMediaOutput mediaOutput = new CreateMediaOutput(listMedia[0], localPath);

 // READ IMAGE FILES
 if (section.ContentType == "image/jpeg")
 {
  while ((section = await reader.ReadNextSectionAsync()) != null)
  {
   var file = section.AsFileSection().FileName;
   string fullPath = Path.Combine(localPath, file);
   FileInfo fileInfo = new FileInfo(fullPath);

   using (var fileStream = new FileStream(fullPath, FileMode.Create))
   {
    await section.Body.CopyToAsync(fileStream);
   }
   mediaOutput.BusnLogicHere(fileInfo, sessionId); // internal busn logic..
  }
 }

 HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.Accepted);
 return msg;
}


text:
Q: Getting Images from theme's directory in pages Yes, I know that we have get_template_directory_uri(); in referencing to the theme's directory. It's working when I put the following code inside index.php or in header.php:
<img src="<?php echo get_template_directory_uri(); ?>/images/sample.png">

But when I'm adding an image inside pages when editing via text, not in visual, it isn't working. How can I get the images from theme's images directory into the pages?
Thanks!

A: <img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?>" alt="" >

Try this. It should work.
You have to concatenate the results from get_template_directory_uri() and your images directory in echo.

A: It's not possible to use PHP code in editor. You can use an image with full path.

In general I would avoid using theme specific images in the content, because when you change and delete the old theme, then they are gone. So I would consider using /wp-content/uploads/ for content images.

A: Shortcode is the way to go, something like this (in functions.php or as plugin) would work:
// [template_dir image="something.jpg"]
add_shortcode( 'template_dir', function( $atts ){
    return get_template_directory_uri() . '/images/' . $atts['image'];
});

A: The answer is yes. You could run php code in editor. But that is not for proper way of adding images. Instead, you should create shortcodes to get those images from theme folder or use like below codes

By removing domain name, it could even benefit of http requests. If removing domain doesn't work, you could even install php wordpress execute plugins. There are some plugins about it. To understand more, you should read this article. I hope that could solve your problems :). Good luck in codes.

A: Didn't Matt announce PHP won't work inside a Wordpress post?

A: get_template_directory_uri()
Quick search through WordPress core code, shows two different treatments. This function needs escaping when it's used inside of tag attribute.
<img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?>" alt="" >
When used inside wp_enqueue_style() or wp_enqueue_script(), it is not escaped:
wp_enqueue_script( 'theme-customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '', true );
However, looking at the function itself, it has filter right before returning values which makes it suspicious – it can be filtered in plugins and we don't know exactly what's returned. Rule of thumb in this situation would be better safe than sorry and always escape.


text:
Q: SDK issues for release in Xcode 9 SDK Version Issue.
This app was built with the iOS 11.4 SDK. All iOS apps submitted to the App Store must be built with the iOS 11 SDK or later,
included in Xcode 9 or later. Further, starting March 2019, all iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later,
included in Xcode 10.1 or later.

I got this issue on release the app to app store.How can I try to solve this?

My development target is 11.4 in Xcode 9

When I tried to change developemt target to 12.1 then I got another more issue


text:
Q: c# Keep file open but overwrite contents I have a 3rd party application that periodically reads output from my C#.Net application.Due to certain constraints, I can only write output to a file which then gets read by the 3rd party application.
I need to overwrite the contents of the same file each time.
I am currently doing it in C# by using
Loop
{
  //do some work
  File.WriteAllText(path,Text);
}

The 3rd party application periodically checks the file and reads the contents. This works well but pushes the CPU usage very high. Replacing File.WriteAllText with a text writer solves the issue of high CPU usage but then my text gets appended to the file instead of overwriting the file.
Could someone point me in the right direction where I can keep a file open in C# and periodically overwrite its contents without too much overhead?
Edit: I fixed the CPU usage by opting to write to the file once every 20 iterations of the loop instead of every iteration of the loop. All the answers given below work but have overhead associated with closing the file and reopening. Thanks

A: Use File.Open with FileMode Truncate to create the file stream for your TextWriter.

A:
Could someone point me in the right direction where I can keep a file open in C# and periodically overwrite its contents without too much overhead?

Here is how I did it in Silverlight 4.  Since you are not using Silverlight, you won't use isolated storage, but same technique will work regardless of the backing store.
The interesting bit is in the Write() method:
logWriter.BaseStream.SetLength(0);

From Stream.SetLength Method:

When overridden in a derived class, sets the length of the current stream.

Be sure to flush the stream using either AutoFlush (as I did in this example), or by adding a logWriter.Flush() after the logWriter.Write().
/// <summary>
/// Represents a log file in isolated storage.
/// </summary>
public static class Log
{
    private const string FileName = "TestLog.xml";
    private static IsolatedStorageFile isoStore;
    private static IsolatedStorageFileStream logWriterFileStream;
    private static StreamWriter logWriter;

    public static XDocument Xml { get; private set; }

    static Log()
    {
        isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        logWriterFileStream = isoStore.OpenFile(
            FileName,
            FileMode.Create,
            FileAccess.Write,
            FileShare.None);
        logWriter = new StreamWriter(logWriterFileStream);
        logWriter.AutoFlush = true;

        Xml = new XDocument(new XElement("Tests"));
    }

    /// <summary>
    /// Writes a snapshot of the test log XML to isolated storage.
    /// </summary>
    public static void Write(XElement testContextElement)
    {
        Xml.Root.Add(testContextElement);
        logWriter.BaseStream.SetLength(0);
        logWriter.Write(Xml.ToString());
    }
}

A: Use the text writer, but clear the contents of the file before you begin writing.  Something like this:
        string path = null;//path of file
        byte[] bytes_to_write = null;
        System.IO.File.WriteAllText(path, string.Empty);
        System.IO.FileStream str = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Write, System.IO.FileShare.Read);
        str.Write(bytes_to_write, 0, bytes_to_write.Length);

Perhaps something from this example will help?

A: Pass false as the append parameter of the constructor:
TextWriter tsw = new StreamWriter(path, false);

Ref: http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx

A: Have you tried using Thread.Sleep?
http://msdn.microsoft.com/en-us/library/system.threading.thread.sleep.aspx


text:
Q: How to change $httpBackend when[method] statements between requests in unit testing? In my testing i initiate some model data and mock the response:
beforeEach(function(){
   var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
   $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
});

it('should find 5000 users in channel 12345', function(){
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000);
});

then say in the next test statement i want the updated value for the channel. Everyone has left, and hypothetically this would trigger other behavior, so i need to mock this second request so i can test that behavioer.
Adding the $httpBackend.whenGET to the next it statment does not override the beforeEach value. It seems to use the original mock value:
it('should find 0 users in channel 12345', function(){
    $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

And if I do it like this without the beforeEach, both fail with the usual "unexpectedGet" error.
it('should find 5000 users in channel 12345', function(){
     var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

it('should find 0 users in channel 12345', function(){
      var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 0); //fails
});

How to modulate mock data between requests?
I also tried:

*

*sandwiching a beforeEach between it statements

*setting a .respond( to a fakeResponse variable. Then changing the fakeResponse value in each it statement.

A: resetExpectations()
Execution
afterEach($httpBackend.resetExpectations);

Documentation

Resets all request expectations, but preserves all backend definitions. Typically, you would call resetExpectations during a multiple-phase test when you want to reuse the same instance of $httpBackend mock.

documentation source: https://docs.angularjs.org/api/ngMock/service/$httpBackend


text:
Q: Is there a way to enforce a size limit of MemoryCache in System.Runtime.Caching? I'm using .net 4 Memory Cache. I would like to limit the size of the cache say to 10mb because I don't want my application to be abusing what goes in there.
I would also like to know how much memory my cache is at any given time. How can I tell at run time?

A: It seems at this time the maximum amount of memory allocated for the cache can not be enforced. See this post for further reference: MemoryCache does not obey memory limits in configuration

A: You can specify the maximum amount of physical memory dedicated to the MemoryCache in the application config file using the namedCaches element, or by passing in the setting when you create your MemoryCache instance via the NameValueCollection passed into the constructor by putting an entry in the collection with a key of cacheMemoryLimitMegabytes and a value of 10.
Here is an example of the namedCaches configuration element:
<configuration>
  <system.runtime.caching>
    <memoryCache>
      <namedCaches>
        <add name="Default"
          cacheMemoryLimitMegabytes="10"
          physicalMemoryLimitPercentage="0"
          pollingInterval="00:05:00" />
      </namedCaches>
    </memoryCache>
  </system.runtime.caching>
</configuration>

And here is how you can configure the MemoryCache during creation:
//Create a name / value pair for properties
var config = new NameValueCollection();
config.Add("pollingInterval", "00:05:00");
config.Add("physicalMemoryLimitPercentage", "0");
config.Add("cacheMemoryLimitMegabytes", "10");

//instantiate cache
var cache = new MemoryCache("CustomCache", config);

This blog post details just about all of the ways to configure the MemoryCache object, and some examples were adapted from this source.

A: You can do this in configuration... for example...
<system.runtime.caching>
   <memoryCache>
      <namedCaches>
         <add name="Default"
              cacheMemoryLimitMegabytes="52"
              physicalMemoryLimitPercentage="40"
              pollingInterval="00:04:01" />
      </namedCaches>
   </memoryCache>
</system.runtime.caching>

To do this in code see... this msdn page


text:
Q: Can we have one uvm_reg_map connected to multiple sequencers I have a situation where I have around 100000 registers in a uvm_reg_block. I have three drivers that can drive transactions to these registers. As per standard UVM RAL methodology, I understand we need three separate uvm_reg_maps connected to three sequencers and drive. The problem is to duplicate the registers in all the three uvm_reg_maps which is eating the CPU time to run. It is taking one hour to even enter the data phase. Can you help me solve this? Is there a way to connect all three sequencers to one uvm_reg_map and somehow based on the argument, decide which physical sequencer it should pick up?
Thanks in advance

A: From what I know, you can't. If one reg map is able to connected to more than one sequencer, then later how can you choose which sequencer to run? In addition, for each added reg map, its handle will be stored inside the uvm_reg's m_maps array via map.add_reg(). It is not like each map will create its own registers, so the registers will not be duplicated.

A: A uvm_reg_map can only work with one sequencer.
You mention that creating multiple reg maps is too slow, because the add_reg(...). It might be possible to separate the register map specification aspect (at what addresses the registers are) from the sequencer aspect. For this you would need one uvm_reg_map instance on which you do your add_reg(...) calls. Let's call this the specification map. For each sequencer you want to drive register accesses on, you would need another uvm_reg_map (sub-class) that somehow points to the specification map. Let's call these driving maps.
I don't have any code on how to do this at the moment. One would need to look at how uvm_reg_map is called by other code and override those functions. Instead of calling the implementations in uvm_reg_map, which deal with its own register storage, they would point to the specification map and interrogate it using get_reg(...) and so on. This might not work if the functions are not declared virtual in uvm_reg_map. UVM has a tendency to make extension impossible because code relies on implementations instead of abstractions.

A: Other way to do is to create a driver which uses all these 3 sequencer/agent.(Let's call it reg_driver)
reg_driver will have one sequencer which gets generic reg. transactions.
From run time switch given, select the reg sequence of interface to drive particular transaction inside reg_driver.


text:
Q: How to sort a collection in Magento? I'm trying to sort a collection by attribute_id. I thought it would be easy, but I think I'm not using it correctly:
$attributes =  Mage::getResourceModel('eav/entity_attribute_collection')
    ->setOrder('attribute_id');
echo $attributes->getSelect();

Result:
SELECT `main_table`.* FROM `eav_attribute` AS `main_table`

Why isn't there any order by?

A: Use this instead of $attributes->getSelect();:
$attributes->getSelect()->order('main_table.attribute_id ASC');

Don't ask why.

A: You're actually doing it the right way. However, since Magento uses EAV, it needs to apply tricks to help performance.
One of these tricks is the timing used to build the eventual SQL string. Usually it's lazily loaded at the last minute and it's not until you actually indicate you want to access a collection's data, that you can see the full SQL used to produce the collection. For example running your code, but prompting magento to actually construct and load the collection, produces the expected output.
$attributes =  Mage::getResourceModel('eav/entity_attribute_collection')
    ->setOrder('attribute_id');
$attributes->count(); // forces the collection to load
echo $attributes->getSelect()->assemble();

This results in the SQL:
SELECT `main_table`.* FROM `eav_attribute` AS `main_table` ORDER BY attribute_id DESC

So you were on the right path, just Magento was doing its level best to confuse you. It's very good at that.


text:
Q: Plotly-Dash: Hide and Unhide Dropdown I would like to launch my Dash with my dropdown hide and after selecting something on another dropdown unhide my first dropdown. Idk if you have any idea, maybe it's a mistake on my little script.
This is a little example :
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash('example')

app.layout = html.Div([
    dcc.Dropdown(
        id = 'dropdown-to-show_or_hide-element',
        options=[
            {'label': 'Show element', 'value': 'on'},
            {'label': 'Hide element', 'value': 'off'}
        ],
        value = 'off'
    ),

    # Create Div to place a conditionally visible element inside
    html.Div([
        # Create element to hide/show, in this case an 'Input Component'
        dcc.Input(
        id = 'element-to-hide',
        placeholder = 'something',
        value = 'Can you see me?',
        )
    ], style= {'display': 'none'} # <-- This is the line that will be changed by the dropdown callback
    )
    ])

@app.callback(
   Output(component_id='element-to-hide', component_property='style'),
   [Input(component_id='dropdown-to-show_or_hide-element', component_property='value')])

def show_hide_element(visibility_state):
    if visibility_state == 'on':
        return {'display': 'block'}
    if visibility_state == 'off':
        return {'display': 'none'}

if __name__ == '__main__':
    app.server.run(debug=False, threaded=True)

A: By slightly changing your code (I changed the parameter that your function takes and using that same parameter in the if statement, this code seems to work). I also change the original style to block, which allows the element to be there, but only shown when on the show dropdown.
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash('example')

app.layout = html.Div([
    dcc.Dropdown(
        id = 'dropdown-to-show_or_hide-element',
        options=[
            {'label': 'Show element', 'value': 'on'},
            {'label': 'Hide element', 'value': 'off'}
        ],
        value = 'off'
    ),

    # Create Div to place a conditionally visible element inside
    html.Div([
        # Create element to hide/show, in this case an 'Input Component'
        dcc.Input(
        id = 'element-to-hide',
        placeholder = 'something',
        value = 'Can you see me?',
        )
    ], style= {'display': 'block'} # <-- This is the line that will be changed by the dropdown callback
    )
    ])

@app.callback(
   Output(component_id='element-to-hide', component_property='style'),
   [Input(component_id='dropdown-to-show_or_hide-element', component_property='value')])

def show_hide_element(value):
    if value == 'on':
        return {'display': 'block'}
    if value == 'off':
        return {'display': 'none'}

if __name__ == '__main__':
    app.server.run(debug=False)


text:
Q: diff -u -s, line cound (+, -) not giving correct value I am using diff -u -s file1 file2 and counting + and - for Added and deleted lines in files for File comparison automation. (Modified lines will also count as one + and one -). These counts match with Araxis tool compare statistics (Total Added+Deleted of script=Changed+deleted+new of Araxis) for most of the files. But script total and Araxis total does not match for few files.
P.S. - I am using cygwin to run script on windows. I tried dos2unix, tail -c 4 etc in hope of removing BOM characters. But out of these culprit files some of them does not have BOM, and still count does not match. Following are few sample culprit files.
(1)SIACPO_ActivacionDesactivacionBlacklist.aspx.vb - Script gives 57 total count, while araxis 55
(2)SIACPO_Suspension_Servicio.aspx - Script gives 2509 total count, while araxis 2473
(3)repCuadreProceso.aspx - Script gives 1165 total count, while araxis 1163
(4)detaPago.aspx.vb - This is strange file. There is no change at all, except BOM character on 1st line. Script gives 0, 0 count, then why at all this in modified list of files??
Now how can I attach these 4 culprint files (Dev as well as Prod version) for your troubleshooting?


text:
Q: Link User Commits to my Github This weekend I was working on a project when my laptop failed. I ended up using a lab computer to code and commit and push work. I authenticated with my GitHub credentials every time, so I assumed the work would be linked to my account. Instead it says U-ACCOUNTS{my_name} as the commit author. I imagine this is because I didn't set the config with my email and name.
Is there any way after the fact to link this to my account. Right now U-ACCOUNTS{my_name} does not even show up on the contributes page.
Thanks.

A: Simply authenticating with your GitHub details isn't enough; what matters is the actual email address listed as the committer for each commit. This is because you could conceivably want to push up a bunch of commits to your account which weren't by you.
I am afraid the only way you'd be able to achieve this is to recomit everything with your correct email address set.


text:
Q: How to I work with window.requestAnimationFrame and yet be able to change it's speed? Is there a way to temporarily modify the speed of something with window.requestAnimationFrame in the middle of say, a classic Snake game?
See the following code:
class Game {

    constructor(snake) {
        this.snake = snake;
    }

    draw() {
        this.snake.slither()
        this.snake.draw()

    }

    start() {
        document.addEventListener("keydown", keyDownEvent);
        let x = 8;
        interval = setInterval(this.draw.bind(this), 1000 / x);
    }

}

In the above example, if I wanted to temporarily change the speed, I would just change the interval speed, and then after setTimeOut, return the speed back to normal.

A: Unfortunately, and for the best, you cannot change the speed of the requestAnimationFrame speed as it is calculated by the browser to ensure a good performance.
You can however, like you described yourself, change an interval speed. But setting setInterval doesn't allow the interval speed to be changed, unless being stopped and restarted. Alternatively you could use a function which uses setTimeout and calls itself after each timeout is being called.
The setTimeout should use a variable or property that is available in all function scopes to use and modify the interval rate.
let timeout = null;
let interval = 0;

function render() {
  // Render your animation.
}

function draw() {
  timeout = setTimeout(() => {
    requestAnimationFrame(render);
    draw();
  }, interval);
}

function stop() {
  if (timeout !== null) {
    clearTimeout(timeout);
  }
}

function changeDrawSpeed(times) {
  interval = 100 * times;
}

draw();

setTimeout(changeDrawSpeed, 1000, 50);
setTimeout(changeDrawSpeed, 3000, 0);

A: Edit: I just forked and edited a bit a previous example of mine for you:
https://jsfiddle.net/ibowankenobi/2k81ya5q/
You can certainly write a routine to control your game frames, I have a small library for instance where I can do:
rafx.async({frame:0})
.animate(function(frames){
   let frame = ++frames.frame;
   if (!(frames % 3)) { //skip every third frame
     return frames;
   }
   //game logic here
}).until(function(frames){
    //return true to quit;
}).then(//whatever follows)

You can also pass additional variables that modify in-run-time how animation changes (frames or whatever).
https://github.com/IbrahimTanyalcin/RafX


text:
Q: to retrieve the Name , Host and SessionId of the of the users with TOP 10 maximum of sessionIds in a particular time

Here is the source Table . I want to retrieve the Name , Host and
  SessionId of the of the users with TOP 10  maximum of sessionIds in a
  particular time
Example
Host          Name           SessionId   NoOfSessionsOpen
   ( 10.42.64.79 ,   thidrat.xyz   ,  tkj7j    ,    4 )

A: select top 10 Name, Host, SessionID, count(*)
from Table
where TimeLog between @a and @b
group by Name, Host, SessionID
order by count(*) desc, Name, Host, SessionID --define a total sort order for determinism


text:
Q: How to use placeholder image, error image with cachedNetworkImageProvider in a container in flutter? This is code snippet of my flutter widget:
Container(
    width: 100.0,
    height: 100.0,
    decoration: BoxDecoration(
    color: Colors.white,
    border: Border.all(
        color: Colors.black.withOpacity(0.1),
        width: 1.0,
    ),
    borderRadius: BorderRadius.circular(8.0),
    image: DecorationImage(
        fit: BoxFit.cover,
        image: CachedNetworkImageProvider(_photoPath),
    ),
    ),
),

I want to set a Placeholder image and an Error image when network image is being loaded or not found on network path.
I am aware about CachedNetworkImage widget which has imageUrl, placeholder and errorWidget attributes but I am not able to use CachedNetworkImage instead of CachedNetworkImageProvider widget because my container's decorationImage image requires CachedNetworkImageProvider as value.
How can I solve this issue?

A: Wrap Your Container in CachedImageNetwork. You can use this
CachedNetworkImage(
  imageUrl: "http://notAvalid.uri",
  imageBuilder: (context, imageProvider) => Container(
        width: 100.0,
        height: 100.0,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: imageProvider,
            fit: BoxFit.cover,
          ),
        ),
      ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
)

A: You can use an external library (CachedNetworkImage) to do so:
CachedNetworkImage(
imageUrl: "http://via.placeholder.com/200x150",
imageBuilder:
(context, imageProvider) =>
    Container(
     decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
          colorFilter:
              ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
     ),
    ),
 placeholder: (context, url) =>
   CircularProgressIndicator(),
 errorWidget: (context, url, error)
  => Icon(Icons.error),
),

Also, If you don't want any external plugin, you can do like below:
 child: new Container(
      child: FadeInImage.assetNetwork(
          placeholder: 'place_holder.jpg',
          image:url
      )
  )

A: if you are using CachedImageNetwork ı just want to change with what is appropriate in your code , NetworkImage , AssetImage etc.. until flutter last version relaised , plugin which is name CachedImageNetwork doesen't work properly.


text:
Q: wordpress Background image is not responsive in mobile devices My website is (https://www.yahoonewsz.com) and I've uploaded an image on the public_html folder in the server.
I have used the following code for background
#main {
  background-image: url("image908.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

in advanced CSS section in WordPress.
Why is the image not responsive in mobile?
Thanks.

A: You're using background-size: cover which according to the background-size docs "Scales the image as large as possible without stretching the image. If the proportions of the image differ from the element, it is cropped either vertically or horizontally so that no empty space remains."
What this means is that it's scaling to the smallest "non-squished" size it can be that prevents any empty space in the container. Since your site (namely the #main) is roughly 3000px tall on mobile, the background image is being scaled to ~3000px tall.
If you want to constrain it to max width, use background-size: contain which "Scales the image as large as possible without cropping or stretching the image." meaning that it will always fill the container without being cut off. Note this will give you white space under (or above) the image based on your background-position settings.


text:
Q: Unable to connect to oracle via Pentaho. 'oracle.jdbc.driver.OracleDriver' could not be found Hi I've just installed Pentaho Data Integration v. 5.01 and I'm trying to connect to a database. However, I'm unable to test the connection as I get the error (pasted below).
I have JDK 1.7 installed on the system as well, however I can't seem to locate ojdbc14.jar anywhere.
I downloaded that and pasted it in pentaho's \lib folder but I still get the same error.
Any solutions to this problem?
Error connecting to database [test] : org.pentaho.di.core.exception.KettleDatabaseException:
Error occured while trying to connect to the database

Driver class 'oracle.jdbc.driver.OracleDriver' could not be found, make sure the 'Oracle' driver (jar file) is installed.
oracle.jdbc.driver.OracleDriver

org.pentaho.di.core.exception.KettleDatabaseException:
Error occured while trying to connect to the database

Driver class 'oracle.jdbc.driver.OracleDriver' could not be found, make sure the 'Oracle' driver (jar file) is installed.
oracle.jdbc.driver.OracleDriver

    at org.pentaho.di.core.database.Database.normalConnect(Database.java:415)
    at org.pentaho.di.core.database.Database.connect(Database.java:353)
    at org.pentaho.di.core.database.Database.connect(Database.java:306)
    at org.pentaho.di.core.database.Database.connect(Database.java:294)
    at org.pentaho.di.core.database.DatabaseFactory.getConnectionTestReport(DatabaseFactory.java:84)
    at org.pentaho.di.core.database.DatabaseMeta.testConnection(DatabaseMeta.java:2459)
    at org.pentaho.ui.database.event.DataHandler.testDatabaseConnection(DataHandler.java:541)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.pentaho.ui.xul.impl.AbstractXulDomContainer.invoke(AbstractXulDomContainer.java:329)
    at org.pentaho.ui.xul.impl.AbstractXulComponent.invoke(AbstractXulComponent.java:139)
    at org.pentaho.ui.xul.impl.AbstractXulComponent.invoke(AbstractXulComponent.java:123)
    at org.pentaho.ui.xul.swt.tags.SwtButton.access$500(SwtButton.java:26)
    at org.pentaho.ui.xul.swt.tags.SwtButton$4.widgetSelected(SwtButton.java:121)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
    at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:820)
    at org.eclipse.jface.window.Window.open(Window.java:796)
    at org.pentaho.ui.xul.swt.tags.SwtDialog.show(SwtDialog.java:375)
    at org.pentaho.ui.xul.swt.tags.SwtDialog.show(SwtDialog.java:301)
    at org.pentaho.di.ui.core.database.dialog.XulDatabaseDialog.open(XulDatabaseDialog.java:115)
    at org.pentaho.di.ui.core.database.dialog.DatabaseDialog.open(DatabaseDialog.java:62)
    at org.pentaho.di.ui.spoon.delegates.SpoonDBDelegate.newConnection(SpoonDBDelegate.java:493)
    at org.pentaho.di.ui.spoon.delegates.SpoonDBDelegate.newConnection(SpoonDBDelegate.java:478)
    at org.pentaho.di.ui.spoon.Spoon.doubleClickedInTree(Spoon.java:2885)
    at org.pentaho.di.ui.spoon.Spoon.access$2300(Spoon.java:332)
    at org.pentaho.di.ui.spoon.Spoon$27.widgetDefaultSelected(Spoon.java:5657)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
    at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
    at org.pentaho.di.ui.spoon.Spoon.readAndDispatch(Spoon.java:1227)
    at org.pentaho.di.ui.spoon.Spoon.waitForDispose(Spoon.java:7368)
    at org.pentaho.di.ui.spoon.Spoon.start(Spoon.java:8673)
    at org.pentaho.di.ui.spoon.Spoon.main(Spoon.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.pentaho.commons.launcher.Launcher.main(Launcher.java:134)
Caused by: org.pentaho.di.core.exception.KettleDatabaseException:
Driver class 'oracle.jdbc.driver.OracleDriver' could not be found, make sure the 'Oracle' driver (jar file) is installed.
oracle.jdbc.driver.OracleDriver

    at org.pentaho.di.core.database.Database.connectUsingClass(Database.java:474)
    at org.pentaho.di.core.database.Database.normalConnect(Database.java:399)
    ... 45 more
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.pentaho.di.core.database.Database.connectUsingClass(Database.java:467)
    ... 46 more

A: Here's my setup. I had this problem and managed to fix it as follows.
I have SQLDeveloper running on my machine and it works OK, even under VPN. However, I was running Spoon and noticed that it wouldn't work if I use VPN.
I have tried to put Oracle JDBC drivers shipped with SQLDeveloper into Pentaho. That didn't work.
However, I noticed that one big difference between SQLDeveloper and Spoon is that they use different
Java runtimes and JDBC Oracle drivers! In particular, my version of SQLDeveloper is running on 32-bit JRE version 1.6.0_11, whereas my system-wide JDK is 64-bit version 1.7.0_03.
I have found the JDBC drivers that SQLDeveloper uses and used them as a replacement for the driver that is shipped with Spoon -- no change.
Then I retargeted Spoon to use the Java runtime used by SQLDeveloper.
I set two environment variables: PENTAHO_JAVA and PENTAHO_JAVA_HOME -- and it works OK now!
For reference, here are my envvars:
PENTAHO_JAVA=C:\opt\sqldeveloper\jdk\jre\bin\java.exe
PENTAHO_JAVA_HOME=c:\opt\sqldeveloper\jdk\jre\

If that is relevant, I am on Windows 7 x64.

A: 1. First go to Oracle Site:
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
2. Download 1 file: ojdbc6.jar
(2,739,670 bytes) - (SHA1 Checksum: a483a046eee2f404d864a6ff5b09dc0e1be3fe6c)
Classes for use with JDK 1.6. It contains the JDBC driver classes except classes for NLS support in Oracle Object and Collection types.
3. Copy it into Pentaho folder: C:\Program Files\Pentaho\data-integration\lib
4. Close Spoon if it is open and re-open again. (transferred from the comment of @mishkin - thanks him)
That works on my Windows 7 X64 Pro with latest Pentaho 5.3 Stable.

A: Try placing the odbc jar file (eg: ojdbc5-11.1.0.7.0.jar) inside the "data-integration/lib" directory of your installation. Don't forget to restart Pentaho to make it work.

A: In Pentaho version 6.0 put the driver (ojdbc6.jar) in: "PentahoInstallation"\design-tools\data-integration\lib and restart the Data Integration ide.

A: See, guys we doesn't need all these stuff. We need to paste oracle jdbc driver (ojdbc6.jar) in the following location.

*

*C:\Program Files\pentaho\design-tools\report-designer\lib\jdbc

*C:\Program Files\pentaho\design-tools\data-integration\lib

*C:\Program Files\pentaho\design-tools\aggregation-designer\lib

*C:\Program Files\pentaho\design-tools\schema-workbench\lib

A: try to put ojdbc driver in libext/JDBC in your PDI path (location)

A: Try putting the jar on tomcat library folder, then restart Pentaho.
Should be here .../biserver-ce-6.0.0.0-353/biserver-ce/tomcat/lib
There are already some drivers here.

A: I could solve this issue by selecting Oralce Native connection > Hostname as Ip address of DB server > instead of SN00XXXX I had used DB00XXX name for the Database name.
I hope this works for such issues with oracle connectivity.

A: In my case, the error was in Report designer
The fix: only copy ojdbc14.jar to
\prd-ce-5.0.1-stable\report-designer\lib
and restart the tool.


text:
Q: In flutter, for how long does the fcm token persist? Specifically I wonder what events would change a device's fcm token? Forcibly closing the app doesn't seem to do it, though I have read somewhere that the token might change. Would it change for a user who uninstalls the app and then reinstalls it?
I would like to reliably send a push notification to a device - without risking the fcm token being changed - as long as the user doesn't intentionally change their token by themselves.
I've spent many hours trying to understand firebase and firebase cloud messaging. To be honest I find the documentation very disappointing, and I'm wondering how to be able to write reliable apps using firebase.

A: You should expect that the FCM token may change for reasons outside of your control.  Flutter is not different than the underlying native system in this respect.  The possible reasons that a token may change are not documented, but your app should be ready to deal with a new token at any time, using the APIs provided.


text:
Q: How to Substract using Posgres within same column I need to subtract the raw data using same column.
The formula is
(provisioned port-shelf x 16 ) - (provisioned summary - provisioned RCMM).

Anyone have idea so that i can improve my query.

A: Assuming I'm understanding your question correctly, given your sample data, your expected result should be 16 for A.  Assuming so, here's one option using conditional aggregation:
select ne,
       max(case when type = 'port-shelf' then 16 * provisioned else 0 end) -
       max(case when type = 'summary' then provisioned else 0 end) -
       max(case when type = 'rcmm' then provisioned else 0 end) as free_slot,
       insert_date
from yourtable
group by ne, insert_date


text:
Q: Change from JS Puppeteer code to PuppeteerSharp C# I have Javascript puppeteer code, and PuppeteerSharp for C#. I know that this libraries are similar, and i know their sites.
But my problem that i barely can manage this libraries, there are alot of methods for each lib, and it hard to find needed methods, even i have working example written on JS.
Please help me rewrite JS code to C#, so it would do similar things. Or at least function names, for example JS (puppeteer) method = C# (puppeteerSharp) method.
(async function main() {
      try {
        const browser = await puppeteer.launch();
        const [page] = await browser.pages();
        page.setDefaultTimeout(0);

        await page.goto('www.example.com');

        await page.waitForSelector('#search-content button.btn-icon');
        let count = 0;
        while (await page.$('#search-content button.btn-icon') !== null && count != 1) {
          const articlesForNow = (await page.$$('#search-content article')).length;
          console.log(`Articles for now: ${articlesForNow}. Getting more...`);
          count += 1;
          await Promise.all([
            page.evaluate(
              () => {
                document.querySelector('#search-content button.btn-icon').click();
              }
            ),
            page.waitForFunction(
              old => document.querySelectorAll('#search-content article').length > old, {},
              articlesForNow
            ),
          ]);
        }

        const articlesAll = (await page.$$('#search-content article')).length;
        console.log(`All articles: ${articlesAll}.`);

        fs.writeFileSync('full.html', await page.content());

        fs.writeFileSync('articles.html', await page.evaluate(
          () => document.querySelector('#search-content div.b-filter__inner').outerHTML
        ));

        fs.appendFileSync('articles.txt', await page.evaluate(
              (fr) => {
                let items = document.querySelectorAll(".product__body");
                let appartmentsData = "";

                for (let i = 0; i < items.length; i++) {
                  let itemLink = items[i].querySelector(".product__link").href;
                  let itemName = items[i].querySelector(".product__link strong").innerHTML;
                  let itemPrice = items[i].querySelector(".product__value").innerHTML;

                  return appartmentsData;
                }, fr
              ));
              // rest of the code

That what I have so far:
using(var browser = await Puppeteer.LaunchAsync(new LaunchOptions())) {
 var page = await browser.NewPageAsync();
 await page.GoToAsync(LINK);
 await page.WaitForSelectorAsync("#search-content button.btn-icon");

 while (await page.QuerySelectorAsync("#search-content button.btn-icon") != null) {
  var articlesForNow = await page.QuerySelectorAllAsync("#search-content article");

  Console.WriteLine("Items proceed: " + articlesForNow.Length);

  for (int i = 0; i < articlesForNow.Length; i++) {
   string itemOuterHtml = await articlesForNow[i].EvaluateFunctionAsync < string > ("e => e.outerHTML");
  }

  await page.WaitForSelectorAsync("#search-content button.btn-icon").EvaluateFunctionAsync("e => e.click()");
 }
}

But It's infinity counting and does not stop. After element is 1275 it throws the error about my method in while loop.
PuppeteerSharp.WaitTaskTimeoutException: waiting for selector '#search-content button.btn-icon' failed: timeout 30000ms exceeded

A: We cannot convert the whole code for you but here are some pointers. You need to take one chunk of problem at a time.
Break the while loop
Let us look into the JS code,
let count = 0;
while (await page.$('#search-content button.btn-icon') !== null && count != 1) {}

It's creating a while look, which stops if count is 1.
Now your C# Code,
while (await page.QuerySelectorAsync("#search-content button.btn-icon") != null)

It's not checking for count, this will end up in infinite while loop.
You should count the number,
int count = 0;
while (await page.QuerySelectorAsync("#search-content button.btn-icon") != null && count != 1){
 // other code
 count++;
}

This way it will stop after it finds one result.
Learn more about Promise.all etc.
Your rest of the question is about Promise.all and few other stuff. Here are some useful links,

*

*Promise.all()

*API Documentation for Puppeteer Sharp

*API Documentation for Puppeteer


text:
Q: In Android, how can i allow the user to choose a color between 4? I'm making an Android App, and i need to put a control that let user choose between 4 different colors. I want to do this with something like radio buttons: the problem is that radiobuttons are round...
is there a way to set them looks like square/rect buttons, and assign a color to their inside rect area ?
If not, how can i achieve that choose for the user ?
I need this because i'm making a Todo/Task android application, and i need the user to choose the priority of a task, between for priority level that are rapresented with a color. So i think to do that by showing 4 buttons, each with a different color associated, and a text inside ("0", "1", "2", "3")
Thanks!

A:
is there a way to set them looks like
  square/rect buttons, and assign a
  color to their inside rect area ?

Step #1: Copy $ANDROID_HOME/platforms/$API/data/res/drawable/btn_radio.xml to your project, where $ANDROID_HOME is where you have installed the Android SDK and $API is some Android platform (e.g., android-2.1)
Step #2: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-hdpi/btn_radio* to your project
Step #3: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-mdpi/btn_radio* to your project
Step #4: Modify those PNG files from steps #2 and #3 to suit your needs


text:
Q: Como criar uma tela de erro 404 Já vi muito tutorial ensinando a personalizar tela de erro 404, mas apenas em CMS como Wordpress, queria saber como eu faço pra estilizar uma página de erro 404*(not found)*, pra que o usuário veja um página bonita, no caso de um link quebrado, ou por qualquer que seja o motivo.
Como faria pra que o navegador abrisse essa minha página 404.html por exemplo em caso de um erro 404?

A: Uma página de erro é como qualquer outra página do seu site, e pode ser criada com as ferramentas tradicionais que você está acostumado, usando HTML, CSS, e mesmo JS se quiser.
Tenha em mente que pela natureza da página, você pode não se limitar a apenas avisar do erro ocorrido. Pelo contrário, é muito mais interessante que, a partir da página de erro, o usuário possa ter a navegação básica para encontrar o que precisa e quem sabe até uma pesquisa automática, como este 404 do php.net, melhorando em muito a experiência do usuário e valorizando o site.
Note alguns detalhes importantes a seguir:
O cabeçalho de status do HTTP
Uma característica importante das páginas de erro, é o cabeçalho HTTP correto. Quando um servidor web envia uma página de erro, há uma informação que é passada ao browser, que é o header de status. Esse cabeçalho não aparece no código-fonte da página, mas é enviado como parte do protocolo HTTP. O status normal é 200, mas em caso de erro ou outras condições especiais, este valor muda.
É importante que o status seja sempre enviado corretamente, pois é através dele que os navegadores, e principalmente os engines de pesquisa como Duck Duck Go, Google, Bing e outros se orientam para indexar corretamente seu site.
Certo, mas como faço para mostrar a página de erro?
Agora entramos no universo dos servidores HTTP. Quando você digita um endereço, como https://pt.stackoverflow.com/a/20739/70, o navegador de internet faz uma requisição de DNS para saber quem é o host responsável pelo endereço pt.stackoverflow.com. Assim que descobre o IP deste host, o navegador faz uma requisição HTTP pedindo o recurso de nome /a/20739/70. Nesta hora, o aplicativo que está servindo as páginas vai utilizar sua metodologia interna para ver se o recurso está disponível, e caso não esteja, ele usará uma página de erro pré-configurada.
Finalmente, para que você possa mostrar a sua nova e criativa página, precisa configurar o servidor para que ele saiba onde ela está. Assim, vamos para a configuração dos servidores HTTP mais comuns:
Configurando o Apache
Esta não pretende ser uma explicação demais detalhada, a ponto de substituir a documentação do Apache, mas é um ponto de partida. Normalmente ao instalar o Apache, há um arquivo de configuração, geralmente com o nome httpd.conf. Neste arquivo, há várias linhas como esta, correspondentes às páginas de erro padrão:
ErrorDocument 404 /404.html

Para utilizar sua página personalizada, basta alterar o caminho /404.html para o local onde você colocou a sua nova página de erro.
Caso você não vá alterar as páginas de erro de todos os sites, mas apenas de alguns, ou mesmo caso não tenha acesso à configuração do Apache, uma saída é criar e/ou modificar um arquivo texto de nome .htaccess (na versão linux) na raiz do site desejado, e incluir os erros personalizados neste arquivo utilizando a sintaxe mencionada, como neste exemplo:
ErrorDocument 404 /meus_erros/erro404.html
ErrorDocument 500 /meus_erros/erro500.html
...

Assim, ao reiniciar o Apache ou recarregar sua configuração, seus erros personalizados devem passar a funcionar no lugar dos originais.

Há vários fatores que influenciam nestas configurações, para maiores detalhes, consulte a documentação do Apache.

Configurando o IIS
No IIS 5.0 a configuração pode ser feita diretamente pelo snap-in do IIS, selecionando o site ou diretório desejado, e clicando em "Propriedades". Em seguida, basta escolher "Erros personalizados", selecionar o erro que deseja alterar, e "Editar propriedades". Aí pode escolher "Arquivo", e apontar o HTML personalizado que criou.
Alternativamente, neste último passo, em vez de "Arquivo" pode escolher "URL", e apontar para um caminho dentro do seu site, caso a página esteja dentro da estrutura de hospedagem. Exemplo /meus_erros/erro404.htm
No IIS 7.5 a solução é parecida, mas o caminho é abrir o IIS Manager, escolher o site desejado, e selecionar o ícone "Páginas de erro .NET", e na barra de ações, clicar na opção de editar, e escolher "ligado". Na tela de edição há um lugar para uma página de erro "geral", e para personalizar individualmente os erros, ainda na barra de ações há o link "Adicionar", para que você escolha o erro desejado e o caminho do respectivo html.
Erros HTTP mais comuns:
Você pode ver uma lista bastante extensa na Wikipedia, mas eis alguns dos erros mais comuns para se personalizar:

*

*401 Não autorizado
Semelhante ao 403, mas especificamente para uso quando a autenticação é possível, mas não foi fornecida ou reconhecida.

*403 Proibido
O pedido foi um pedido legal, mas o servidor está se recusando a responder. Por exemplo, ao se tentar visualizar uma pasta protegida.

*404 Não encontrado
O clássico "Not found", página não encontrada.

*500 Erro interno do servidor
Indica um erro do servidor ao processar a solicitação. Na grande maioria dos casos está relacionada as permissões dos arquivos ou pastas do software ou script que o usuário tenta acessar, ou mesmo problemas na configuração do servidor web.

A: Você deve criar uma configuração para isso. Você pode colocar esta configuração no seu server web (Apache, Nginx...), ou colocar essa configuração na própria aplicação: você irá verificar se o usuário tentou acessar uma url válida, senão você manda exibir o 404.html. Quando se constrói uma aplicação web, é bem comum utilizar algum Framework (Zend, Symphony, Cake...), e eles já possuem tudo prontinho para você apenas se preocupar com o HTML e CSS desta página. Senão, você terá que fazer este redirecionamento manualmente. Como você colocou a tag PHP na pergunta, imagino que esteja fazendo um site com PHP, certo? Bem, você deve ter algum lugar para colocar as rotas(urls válidas) do site, certo? Está utilizando algum framework? Está fazendo tudo "na mão"?
Se você utiliza um framework como AngularJS ou EmberJS, no caso de estar criando uma aplicação JS, pode fazer esta verificação no cliente mesmo, e não no servidor.
Bem, dê mais detalhes da sua aplicação, assim é mais fácil dar o caminho =)


text:
Q: Storing a variable size JSON array in an iOS element {
  "bidstatus":[
        {"bidstatusid":"1","bidstatus":"Quoted"},
        {"bidstatusid":"2","bidstatus":"Closed"},
        {"bidstatusid":"3","bidstatus":"Awarded"}
        ],
  "config":{
        "adminfee":"100",
        "percentcommission":"10",
        "premiumfee":"0"
        },
  "lvlsubj":{
        "Primary 1":["English","Geography","Maths","Science"],
        "Primary 2":["English","Geography","History"],
        "Primary 3":["Maths","Science"]
        }
}

I have an incoming JSON reply from an API which returns the above.  Existing iOS code uses AFNetworking to parse the JSON.  I'm able to store bidstatus as NSArray and config as NSDictionary.  However, I can't get lvlsubj to be stored properly.  This object looks like a 2D array with the second level array of variable size.
How do I go about it?
The existing code is pretty straightforward.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString* strRequestLink = [NSString stringWithFormat:@"%@%@", SERVICEPATH, @"get_var.php"];
[manager GET: strRequestLink
  parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"JSON: %@", responseObject);
         [GlobalPool sharedObject].m_dictPaymentConfig = [[responseObject valueForKey:@"config"] mutableCopy];
         [GlobalPool sharedObject].m_arrayBidStatus = [[responseObject valueForKey:@"bidstatus"] mutableCopy];
         //[GlobalPool sharedObject].m_arrayLevelSubject = [[responseObject valueForKey:@"lvlsubj"] mutableCopy];

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);

         [self showServerConnectionError];
     }];

A: Thanks to the suggestions above, I managed to get them stored and read.
Store it as NSDictionary.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString* strRequestLink = [NSString stringWithFormat:@"%@%@", SERVICEPATH, @"get_var.php"];
[manager GET: strRequestLink
  parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"JSON: %@", responseObject);
         [GlobalPool sharedObject].m_dictPaymentConfig = [[responseObject valueForKey:@"config"] mutableCopy];
         [GlobalPool sharedObject].m_arrayBidStatus = [[responseObject valueForKey:@"bidstatus"] mutableCopy];
         [GlobalPool sharedObject].m_dictLevelSubject = [[responseObject valueForKey:@"lvlsubj"] mutableCopy];

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);

         [self showServerConnectionError];
     }];

Then use allKeys to store keys in NSArray. Using the keys, read from NSDictionary (which will return array).
The code here populates a picker with the keys.  Upon selecting a value, it will read from the NSDictionary to get the corresponding object (NSArray) and populate a second picker.
- (IBAction)actionChooseLevel:(id)sender {
    NSArray* arrayKeys = [[GlobalPool sharedObject].m_dictLevelSubject allKeys];
    if (arrayKeys.count == 0)
        return;

    [arrayPickerItems removeAllObjects];
    for (int nIdx = 0; nIdx < arrayKeys.count; nIdx++)
    {
        NSMutableString* strInfo = [arrayKeys objectAtIndex:nIdx];
        [arrayPickerItems addObject:strInfo];
    }

    [ActionSheetStringPicker showPickerWithTitle:@"Choose Level" rows:arrayPickerItems initialSelection:nSelectedLevelIdx > 0 ? nSelectedLevelIdx : 0 target:self successAction:@selector(itemWasSelected:element:) cancelAction:@selector(actionPickerCancelled:) origin:sender];
}

- (IBAction)actionChooseSubject:(id)sender {
    NSArray* arrayObject = [[GlobalPool sharedObject].m_dictLevelSubject objectForKey:self.m_lblSelectedLevel.text];
    if (arrayObject.count == 0)
        return;

    [arrayPickerItems removeAllObjects];
    for (int nIdx = 0; nIdx < arrayObject.count; nIdx++)
    {
        NSMutableString* strInfo = [arrayObject objectAtIndex:nIdx];
        [arrayPickerItems addObject:strInfo];
    }

    [ActionSheetStringPicker showPickerWithTitle:@"Choose Subject" rows:arrayPickerItems initialSelection:nSelectedSubjectIdx > 0 ? nSelectedSubjectIdx : 0 target:self successAction:@selector(itemWasSelected:element:) cancelAction:@selector(actionPickerCancelled:) origin:sender];
}


text:
Q: How do I remove a clearcase merge arrow in Clearteam Explorer? Removing merge arrows and versions of files is straightforward using the ClearCase CLI.  However, I only can manipulate our UCM via the Eclipse Clearteam Plugin and I do not have access to the command line.
Right now the version tree in the area I want to manipulate looks like this:

For reference, here is the toolbar that I have at the ready.  The help menu only described how to make merges, not cancel them:

How do I remove a merge through the Clearteam application shown?

A: There is not much option that doing the equivalent of a cleartool rmver of the target version of the merge arrow. (right-click on the target version, and select delete)
And that would even not be enough, as ClearCase should refuse the rmver, considering the version is reference by the merge hlink, or part of other UCM metadata (baselines, stream, ...)
If that is the case, then the GUI alone would not be enough, as opposed to the CLI rmver -xhlink.
You might consider adding a custom action menu to your ClearTeam Explorer in order to try and replicate the rmver -xhlink using the CM API (libraries and documentation are an option when you install ClearCase), but I don't know if said library can go that far.

A: If you're using web views and can only work in the GUI, there isn't a way to remove any type of hyperlink.
Nor does the rcleartool command support the rmhlink command. rcleartool doesn't allow rmver either. All you can do is remove the version.


text:
Q: conditional expectation of gaussian random variable Let $(X_1, \ldots , X_n)$ be a gaussian random vector with zero mean and covariance matrix $B$.  Find the distribution of the random vector $E(X_1 \mid X_2, \ldots, X_n)$.  I am not sure how to proceed.  Thanks in advance.

A: You can find formulas for the conditional distributions from a Gaussian vector.
In particular, if $B=\begin{bmatrix} B_{11} & B_{12} \\ B_{12}^\top & B_{22} \end{bmatrix}$ where $B_{11}$ is $1 \times 1$ and $B_{22}$ is $(n-1) \times (n-1)$, then the conditional expectation is
$$E[X_1 \mid X_2 ,\ldots, X_n] = B_{12} B_{22}^{-1} \begin{bmatrix}X_2 \\ X_2 \\ \vdots \\ X_n \end{bmatrix}.$$
This is a linear transformation of the Gaussian vector $(X_2, \ldots, X_n)$ to a univariate random variable, so the distribution is univariate Gaussian. I'll leave it to you to compute the mean and variance of this univariate Gaussian.


text:
Q: how to find out all the checked out files in a branch As title, could anyone of you  give me a working instruction to solve that problem ?
thanks a lot!

A: $ ct lsco -brtype your-branch-type-selector

A: If you only after checked-out files and you are in a dynamic view set to see only MY_BRANCH:
ct lsprivate -co .

(with '.' being the parent directory under which you want to find co files)
That command is recursive by default.
Your config spec would need to be
element * CHECKEDOUT
element * .../MY_BRANCH/LATEST
element -directory /main/LATEST

With checked-out files and directories in a snapshot or dynamic view, use indeed lsco, but knowing that command is not recursive by default. So I would recommend:
ct lsco -rec -brtype MY_BRANCH

A: Start by having a look here : IBM ClearCase Command Reference : lscheckout
Then, as an example, try this...
If your branch was foo, and your are in the VOB you want to check, you can run
  ct lsco -brtype foo

or
  ct lsco -brtype brtype:foo


text:
Q: how to call a method automatically in every seconds using spring boot? In Spring-boot project, is there a method that want to make it called every seconds automatically?
And make an rest-api to set calling term in same project?

A: Here comes an example.
The greeting method will be executed every 5 seconds and it can be called when you visit /hello endpoint.
@SpringBootApplication
@EnableScheduling
@RestController
public class So47301079 {
    public static void main(String[] args) {
        SpringApplication.run(So47301079.class, args);
    }

    @Scheduled(fixedRate = 5000)
    @GetMapping(value="/hello")
    public void greeting() {
        System.out.println("Hello!!!");
    }
}

Hope this helps you!

A: Can use cron expression like @Scheduled(cron="*/5 * * * * *"). In this way, we have a control on minutes, hours, days also. Have a look at this video to know different possible ways to use cron expression.


text:
Q: Interesting problem from symmetric group: Interesting problem from symmetric group:
For $ \ n \geq 3 \ $ , if $ \ \alpha \in S_n \ \ define \ \ \alpha' \in S_{n+2} \ $ by $  \begin{Bmatrix} \alpha'(i)=\alpha(i) \ \ 1 \leq i \leq n \\ \alpha'(n+1)=n+1 \ \ \ \ \ \ \ \ \ \\ \alpha'(n+2)=n+2 \ \ \
\ \ \ \ \  \end{Bmatrix} $
Define $ \phi : S_n \rightarrow S_{n+2} $ by
$ \ \ \phi(\alpha)=\alpha ' \ \ if \ \ \alpha \in A_n \ \ $ and
$ \phi(\alpha)=\alpha' \beta \ \ if \ \ \alpha' \notin A_n \ \ for \ \ \beta= (n+1 \ \ \  n+2) \ cycle $
(a)  Prove that  $ \ \phi \ $ is homomorphism .
(b) Prove that $ \ \ \phi(S_n) \leq A_{n+2} \ $.
My approach :
(a)  Let $ a , \ b \in S_n $ .  If $ a,b \in A_n , then \ \ ab \in A_n , \ \ because \ \ A_n \ \ forms \ a \ group . $
Then $ \ \phi(ab)(i)=(ab)'(i)=(ab)(i)=a(i) b(i)=a'(i) b'(i)=\phi(a) \phi(b)(i) $
or, $ \phi(ab)=\phi(a) \phi(b) $.
Hence $ \phi \ is \ a \ homomorphism . $
I think for the part (b) we have to show that $ \ \phi:S_n \rightarrow A_{n+2} $ is an Injection map  . But I am unable to show.
Am I right ? Any help for the second part ?

A: To show part (b)(i.e., $\phi(S_n)\subset A_{n+2}$), I think it is enough to show that the image of the function $\phi$ lies in $A_{n+2}$ i.e., to show that $\phi(\alpha)\in A_{n+2}$ for all $\alpha \in S_n$.
Take any $\alpha \in S_n$. Then either $\alpha \in A_n$ or not. Observe that, by the definition of $\phi$ and $\alpha^{\prime}$ in either case the image is an even permutation in $S_{n+2}.$ Can you see that?

A: a-)
To show that $\phi$ is an homomorphism, let $\alpha_1, \alpha_2 \in S_n$.
If $\alpha_1, \alpha_2 \in A_n$.Then since $\alpha_1 \circ \alpha_2 \in A_n$,
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1 \circ \alpha_2)^{'} = (\alpha_1)^{'} (\alpha_2)^{'}$$
If, without lost of generality, $\alpha_1 \not \in A_n$ and $\alpha_2 \in A_n$,
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1 \circ \alpha_2)^{'} \circ \beta = (\alpha_1^{'}) (\alpha_2^{'}) \beta$$
since $(n+1)$ and $(n+2)$ are fix in $\alpha_2$,
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1^{'})\beta (\alpha_2^{'}$$
If $\alpha_1, \alpha_2 \not \in A_n$, then
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1 \circ \alpha_2)^{'}= \alpha_1^{'} \circ \alpha_2^{'}$$
since $\alpha_1 \circ \alpha_2 \in A_n$.
b-)
Note that in all of the if statements above, $\phi (...) \in A_n$, and for the rest, I think it is clear.


text:
Q: How to debug in VSCode with multiple command line arguments and the difference between launch.json and tasks.json? I would like to use the VSCode debugger rather than just plain gdb in the terminal. The particular program I want to debug takes in two command line arguments, and when researching how to take these arguments into account when working with the VSCode debugger, all sources said to place them in the "args" section in launch.json. No matter how I set up the launch.json and tasks.json files, I get a 'executableName not found' error when I run the debug. It shows the path the debugger took to reach the specified executable file, and I have verified that the file does in fact exist in the exact place the debugger's error message said it deosn't.
The executable is the product of a Makefile written by my instructor, which, as far as I am aware, should append all possible arguments to the test-get-sum executable? I am new to makefiles and c++ as a whole, so I have a strong feeling I am very wrong about this.
I believe that the error is of my own ignorance, as I am not sure how to properly configure the VSCode debugging environment for C++, especially when it comes to projects with multiple files and headers that need to be compiled together. There was another question asked a few years back pertaining to the matter of C++ debugging in VSCode, following those instructions and the other solutions also did not work for me. The two error messages I get are along the lines of 'file not found' or 'file format unsupported.' After researching, I am also still unsure of the technical differences between tasks.json and launch.json.
My launch.json file
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/test-find-sum",
            "args": ["dat/row_matrix.txt", "1"],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description":  "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ]
        }

    ]
}

my tasks.json file
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

the Makefile, for information's sake
# use g++ compiler
cc = g++

# add parent to include path and root
path = ..

# compile with C++ 17 standard
flags = -std=c++17
# compile with all warnings
flags += -Wall
# compile with PWD appended to compiler library path
flags += -I $(path)
# compile with debug instrumentation
flags += -g

# compile, assemble, link
link = $(cc) $(flags) -o
# compile, assemble, do not link
compile = $(cc) $(flags) -c

test-find-sum : bin/test-find-sum.o bin/find-sum.o
    $(link) $@ $^

test-find-sum-all : test-find-sum
    @echo 'Running All Tests' \
  && ./test-find-sum dat/row_matrix.txt 0  \
    && ./test-find-sum dat/col_matrix.txt 1  \
    && ./test-find-sum dat/asc_matrix.txt 2  \
    && ./test-find-sum dat/dsc_matrix.txt 3  \
    && ./test-find-sum dat/matrix.txt 4  \
    && ./test-find-sum dat/matrix.txt 5  \
    && ./test-find-sum dat/large_matrix.txt 6  \
    && echo 'Passed All Tests'

test-find-sum-style : src/find_sum.cpp inc/find_sum.h
    cpplint --root=$(path) $^

test-find-sum-memory : test-find-sum
    @echo MEMORY TEST 0
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/row_matrix.txt 0 > /dev/null
    @echo MEMORY TEST 0 PASSED
    @echo MEMORY TEST 1
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/col_matrix.txt 1  > /dev/null
    @echo MEMORY TEST 1 PASSED
    @echo MEMORY TEST 2
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/asc_matrix.txt 2 > /dev/null
    @echo MEMORY TEST 2 PASSED
    @echo MEMORY TEST 3
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/dsc_matrix.txt 3  > /dev/null
    @echo MEMORY TEST 3 PASSED
    @echo MEMORY TEST 4
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/matrix.txt 4  > /dev/null
    @echo MEMORY TEST 4 PASSED
    @echo MEMORY TEST 5
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/matrix.txt 5 > /dev/null
    @echo MEMORY TEST 5 PASSED
    @echo MEMORY TEST 6
    valgrind --leak-check=full --error-exitcode=1 \
    ./test-find-sum dat/large_matrix.txt 6 > /dev/null
    @echo MEMORY TEST 6 PASSED
    @echo ALL MEMORY TESTS PASSED

bin/test-find-sum.o : src/test_find_sum.cpp inc/test_find_sum.h \
                        inc/find_sum.h
    $(compile) -o $@ $<

bin/find-sum.o : src/find_sum.cpp inc/find_sum.h
    $(compile) -o $@ $<

clean:
    $(RM) bin/* test-find-sum


text:
Q: proc sql join in do loop with macro I am trying to join over 15 tables and I wrote a macro which has two do loops and the program I wrote is this way.
%macro joinnow (year, Tno);
%do year=1991 %to 2012;
%do Tno=2 % to 23;
Full join A_&year T&Tno ON T1.ID=T&Tno.ID
%End;
%End;
%mend;

Now I run the program
Proc sql;
create table NEW_tab as
    Select T1.*, T2.reg_1991,-----,T23.reg_2012
    from  A_1990 T1
    %joinnow;
;
Quit;

I get an error saying
ERROR: Column reg_2002 could not be found in the table/view identified with     the correlation name T13.

where as the reg_2002 is present in T13
Can you see where the error is?


text:
Q: Can we rearrange the alternating harmonic series and make it equal to arbitrary real number? By "Riemann Rearrangement Theorem", we can rearrange the conditionally convergence series and make it equal to arbitrary value.
And Riemann showed that rearranging the alternating harmonic series by $ {1 \over 2} \ln(2) $.
But I wondered what specific way to rearrange the certain series by arbitrary value.
such as:
$$ 1 - {1 \over 2} + {1 \over 3} - {1 \over 4} + \cdots \text{ → (Rearrange)} = N, $$
$$ \text{where } N \text{ is arbitrary real number} $$
Is there a specific way?
Thank you for reading.

A: You have
$$
1 + \frac 1 3 + \frac 1 5 + \frac 1 7 + \cdots = +\infty
$$
$$
-\frac 1 2 - \frac 1 4 - \frac 1 6 - \frac 1 8 - \cdots = -\infty
$$
Suppose I want a rearrangement that makes the sum equal to $10.$
Keep adding up odd terms until the sum exceeds $10.$ Then add one even term so that the sum is less than $10.$ Then keep adding up odd terms until the sum exceeds $10.$ Then add one even term so that the sum is less than $10.$ Then keep adding up odd terms until the sum exceeds $10.$ Then add one even term so that the sum is less than $10.$ And so on.
This will converge to $10.$


text:
Q: Why does Windows Easy Transfer say I shouldn't use either computer while in progress? I'm transferring files from my old Windows 7 laptop to a new Windows 7 laptop using Windows Easy Transfer over my home wireless network.
It's been going for 24 hours now and is making slow progress (it's got 1 day 3 hours remaining).
It says I can't use either computer during transfer but I wonder is it because it will slow it down or will it cause errors?

A: Because ANYTHING you do might change things on your hard drive, things that Easy Transfer may or may not care about. This may - repeat MAY - cause errors. If you want a clean copy of your files and settings, follow the instructions.

A: It could slow the transfer down (even more) since you'll be using system resources (disks, memory, CPU, network, etc.) for your tasks as well. This may not be much of an impact though, depending on what you're doing.
You also increase the risk of you interrupting the transfer, and causing it to stop before it's done.
Additionally you may end up not transferring files you change, because it packed them already.
Otherwise, go ahead. :)