text:
Q: Laravel faker generate gender from name What is the optimum way of generating gender using faker, having generated a name so that the gender matches the name
 return [
    'name' => $faker->name,
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $faker->randomElement(['male', 'female']),//the gender does not match the name as it is.
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
    ];

A: to do it without additional variable, do it like this
return [
  'gender' => $faker->randomElements(['male', 'female']),
  'name' => $faker->name(function (array $user) {return $user['gender'];})
]

hope it helps

A: *

*The method randomElements is gonna return an array with one single element, so if you want to get 'female' or 'male', don't forget to add at the end of the first line this: [0]. You need the first element (index 0) of the resulting array (that only has one element).
 $gender = $faker->randomElements(['male', 'female'])[0];

*One more thing. In order to obtain exactly what you want, you need to use firstName instead of name. This way the first name will be according to the gender. Do it this way:
 return [
     'name' => $faker->firstName($gender),
     'email' => $faker->safeEmail,
     'username' => $faker->userName,
     'phone' => $faker->phoneNumber,
     'gender' => $gender,
     'address' => $faker->address,
     'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
     'password' => bcrypt('secret')
 ];

*One last thing: If you use 'Male' and 'Female', instead of 'male' and 'female', this is NOT gonna work!!

A: Looking at the documentation and an issue raised on the their Github issues section, your solution seems to be the best. Some methods allow you to specify the gender for a name so you could do like this:
$gender = $faker->randomElement(['male', 'female']);

return [
    'name' => $faker->name($gender),
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $gender,
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
];

Hopefully this fits your requirement.

A: Actually all answers did not really work for me. It returned female or male only.
I had almost the same issue. I needed a random element out of three genders . It always gave me this error message:
 Illuminate\Database\QueryException  : Array to string conversion (SQL: insert
 into `users` (`name`, `gender`, `email`, `admin`, `author`, `password`,
 `remember_token`) values (Margaret Robel I, male, azieme@example.com, 1, 0,
 dummylogin, gwKdVN7zYv))

 at /Users/mangrove/Desktop/php-workspace/laravel-
 mangrove/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
 660|         // If an exception occurs when attempting to run a query, we'll
 format the error
 661|         // message to include the bindings with SQL, which will make this
 exception a
 662|         // lot more helpful to the developer instead of just the
 database's errors.
 663|         catch (Exception $e) {
 > 664|             throw new QueryException(
 665|                 $query, $this->prepareBindings($bindings), $e
 666|             );
 667|         }
 668|

 Exception trace:

 1   ErrorException::("Array to string conversion")
 /Users/mangrove/Desktop/php-workspace/laravel-

 mangrove/vendor/laravel/framework/src/Illuminate/Database/
 MySqlConnection.php:80

 2   PDOStatement::bindValue()
 /Users/mangrove/Desktop/php-workspace/laravel-

 mangrove/vendor/laravel/framework/src/Illuminate/
 Database/MySqlConnection.php:80

After a look at the documentation for Faker v.1.8.0
This worked for me:
public function run()
{
  $faker = Faker::create();
  foreach(range(1,10) as $index){

    // Returns always random genders according to the name, inclusive mixed !!
    $gender = $faker->randomElement($array = array('male','female','mixed'));

    DB::table('users')->insert([
          'name' => $faker->name($gender),
          'gender' => $gender,
          'email' => $faker->unique()->safeEmail,
          'admin' => $faker->numberBetween($min = 0, $max = 1),
          'author'=> $faker->numberBetween($min = 0, $max = 1),
          'password' => 'dummylogin',
          'remember_token' => str_random(10),
    ]);
  }
}

It turns out mixed genders will always have different names, because you can
be either way ⚧


text:
Q: PyCharm couldn't find a pre-installed module os but can still use it I've using Pycharm for a while now. And recently I noticed that the import os line is highlighted in red with an error message of No module named os. (Using Python 3.8.4)

But when launching the script(Via PyCharm) it's importing it without any errors.
The exact same thing is also happening with a module named webbrowser.
Why does it say this? And how do I fix this?

A: I am using the Python from the Microsoft Store. And changing the Interpreter from ...\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe to ...\AppData\Local\Microsoft\WindowsApps\python.exe fixed it.
(The first directory gave me an invalid SDK error)
Or maybe just the fact that I remove and added back the Interpreter was the thing that fixed it.

A: I am using python 3.8.5 on a mac, and found the trick to be to quit pycharm, delete the .idea file in the project directory and restart pycharm.

redpajama_set_name: RedPajamaStackExchange


text:
Q: R data.fame manipulation: convert to NA after specific column I have a large data.frame and I need some conversion based by row. My purpose is convert all values in rows to NA after if there is specific character in column.
For example I provide little sample from my real data set:
sample_df <- data.frame( a = c("V","I","V","V"), b = c("I","V","V","V"), c = c("V","V","I","V"),  d = c("V","V","I","V"))

result_df <- data.frame( a = c("V","I","V","V"), b = c("I",NA,"V","V"), c = c(NA,NA,"I","V"), d = c(NA,NA,NA,"V"))

As an example in sample_df
First I want to turn all values to NA after first "I"
Sample data.frames
I tried base, dpylr, purrr but can not create an algorithm.
Thanks for your help.

A: Try this:
Find "I" values
I_true<-sample_df=="I"
I_true
         a     b     c     d
[1,] FALSE  TRUE FALSE FALSE
[2,]  TRUE FALSE FALSE FALSE
[3,] FALSE FALSE  TRUE  TRUE
[4,] FALSE FALSE FALSE FALSE

Find positions from the first "I" seen
out<-t(apply(t(I_true),2,cumsum))
    out
     a b c d
[1,] 0 1 1 1
[2,] 1 1 1 1
[3,] 0 0 1 2
[4,] 0 0 0 0

Replace needed values
 output<-out
 output[out>=1]<-NA
 output[output==0]<-"V"
 output[I_true]<-"I"
 output[out>=2]<-NA

Your output
output
     a   b   c   d
[1,] "V" "I" NA  NA
[2,] "I" NA  NA  NA
[3,] "V" "V" "I" "I"
[4,] "V" "V" "V" "V"

Example 2:
sample_df <- data.frame( a = c("V","I","I","V"), b = c("I","V","V","V"), c = c("V","V","I","V"), d = c("V","V","I","V"))
sample_df
  a b c d
1 V I V V
2 I V V V
3 I V I I
4 V V V V
output
     a   b   c   d
[1,] "V" "I" NA  NA
[2,] "I" NA  NA  NA
[3,] "I" NA  NA  NA
[4,] "V" "V" "V" "V"

A: Here is a brute force approach, which should be the easiest to come up with but the least preferred. Anyway, here it is:
df <- data.frame( a = c("V","I","V","V"), b = c("I","V","V","V"), c = c("V","V","I","V"),  d = c("V","V","I","V"), stringsAsFactors=FALSE)
rowlength<-length(colnames(df))
for (i in 1:length(df[,1])){
   if (any(as.character(df[i,])=='I')){
      first<-which(as.character(df[i,])=='I')[1]+1
      df[i,first:rowlength]<-NA
   }
}

A: Here's a possible answer using ddply from the plyr package
ddply(sample_df,.(a,b,c,d), function(x){
  idx<-which(x=='I')[1]+1 #ID after first 'I'
  if(!is.na(idx)){    #Check if found
    if(idx<=ncol(x)){  # Prevent out of bounds
      x[,idx:ncol(x)]<-NA
    }

  }
  x
})

A: The plyr approach :
plyr::adply(sample_df, 1L, function(x) {
  if (all(x != "I"))
    return(x)
  x[1L:min(which(x == "I"))]
})

You have to use an if because x[min(which(x == "I"))] would returns numeric(0) for rows without at least one I

A: My Solution:
After @Julien Navarre recommendation, first I created toNA() function:
toNA <- function(x) {

  temp <- grep("INVALID", unlist(x)) # which can be generalized for any string

  lt <- length(x)
  loc <- min(temp,100)+1 #100 is arbitrary number bigger than actual column count

  #print(lt) #Debug purposes

  if( (loc < lt+1) ) {
    x[ (loc):(lt)] <-NA
  }

  x

}

First, I tried plyr::adply() and purrrlyr::by_row() functions to apply my toNA() function my data.frame which has over 3 million rows.
Both are very slow. (For 1000 rows they take 9 and 6 seconds respectively). These approaches are also slow with a simple function(x) x. I am not sure what is overhead.
So I tried base::apply() function: (result is my data set)
as.tibble(t(apply(result, 1,  toNA ) ))

It only takes 0.2 seconds for 1000 rows.
I am not sure about programming style but for now this solution works for me.
Thanks for all your recommendations.

A: A pure base solution, we're building a boolean matrix of "=="I" or not", then with a double cumsum by row we can find where our NAs must be placed:
result_df <- sample_df
is.na(result_df) <- t(apply(sample_df == "I",1,function(x) cumsum(cumsum(x)))) >1

result_df
#   a    b    c    d
# 1 V    I <NA> <NA>
# 2 I <NA> <NA> <NA>
# 3 V    V    I <NA>
# 4 V    V    V    V


text:
Q: SaveFileDialog bug in WPF I'm using Microsoft.Win32.SaveFileDialog class to save my files. When I saved file, and minimize my app, I can't restore it back. It happens only after when used Microsoft.Win32.SaveFileDialog. Here is code:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = String.Format("{0} {1} {2}", ev["b"], ev["a"], ev["c"]);
dlg.DefaultExt = ".csv";
dlg.Filter = "Supported format (.csv)|*.csv";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
    string s = dlg.FileName;
    //other code
}

File saves successfully, but I don't know how to solve problem with minimizing. Does anybody knows what it could be?

A: WPF has all kinds of weird modality issues when you show dialogs without parent windows. I haven't seen this directly with the SaveFileDialog, but I have seen similar behavior with other dialogs. Try using the overload of .ShowDialog() where you pass in the parent window.

A: I encountered also a strange modality problem with WPF and the Win32 SaveFileDialog / OpenFileDialog.
What happens:

*

*The modal state is violated / gets lost completely and the main window can be clicked while the OpenFileDialog is opened with ShowDialog()

When does it happen:

*

*There was a task running before the OpenFileDialog opens

*The debugger breaks into a breakpoint before running the task

Just create a simple WPF Application with a button click event:
    private void Button_Click(object sender, RoutedEventArgs e)
    { // <-- Breakpoint sits here

        Task.Run(() => {}).Wait();

        new Microsoft.Win32.OpenFileDialog().ShowDialog();
    }

Using the overloaded ShowDialog(Window owner) function solves this problem.


text:
Q: Legacy Geocoder Retiring - Alternatives to ESRI World Geocoder Knowing that ESRI is retiring their legacy geocoding systems, what good alternatives for batch geocoding do you know of?

A: Nominatim from openstreet map provides free geocoding:  http://wiki.openstreetmap.org/wiki/Nominatim
Most country's only up to street level.
Cloudemade has a commercial solution.
http://cloudmade.com/products/geocoding


text:
Q: MVC3 jQuery - partial validation I have a form in which a user enters 2 types of data:
1. Project details
2. Survey questions related to the project
The form has 2 submit buttons
1. Save Draft
2. Submit
The 'Save Draft' post needs to validate only project details and not survey fields. The Submit post should validate both project and survey data.
Is there a way to partially validate data when user clicks 'Save Draft'? Maybe handle the 'Save Draft' click and ignore/remove validation for the survey fields...

A: You can do partial validation by with an action filter attribute. You might be able to customize to your needs. It gives you access to the request and the model state. With access to the model state you can modify the validation errors.
public class ValidateDraftAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {

     var modelState = filterContext.Controller.ViewData.ModelState;
     var incomingValues = filterContext.Controller.ValueProvider;

      modelState[key].Errors.Clear();

  }
}

The attribute is then added to the controller.


text: Q: 2 different view types, one app I have been working on an app for iPad with two different view types, half of it utilizes viewbased to connect to a server over a wireless network.  The other half utilizes a split view controller to show core data retreaved from the server.  I have been working on the two different parts independently to insure that I could understand how each worked.  I'm having trouble jumping between the two views. The question of the day for me is, is it even possible to combine two different sets of views?


text:
Q: Is it possible to log the server certifcate in PEM format with javax.net.debug? I'm troubleshooting some SSL/TLS problems, with -Djavax.net.debug on the command line and it would help immensely to have some logging where the server certificate is logged in a format which can be parsed and read.
I tried following debug settings:
-Djavax.net.debug=ssl:record:plaintext
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager
-Djavax.net.debug=ssl:handshake:verbose

The closed I came was with the last statement which logs the following:
10/11/2021 10:27:36    "version"            : "v3",
10/11/2021 10:27:36    "serial number"      : "I8 00 00 00 00 D2 91 BH 88 A4 10 58 00 00 02 00 04 9E 4B",
10/11/2021 10:27:36    "signature algorithm": "SHA256withRSA",
10/11/2021 10:27:36    "issuer"             : "CN=test, DC=test, DC=test, DC=com",
10/11/2021 10:27:36    "not before"         : "2021-07-23 17:38:30.000 UTC",
10/11/2021 10:27:36    "not  after"         : "2026-07-22 17:38:30.000 UTC",
10/11/2021 10:27:36    "subject"            : "CN=CNTest, OU=TIS, O="ACME Inc", L=France, ST=Paris, C=EU",
10/11/2021 10:27:36    "subject public key" : "RSA",
10/11/2021 10:27:36    "extensions"         : [
...
]

Which is already useful but it would help immensely to have the server certificate in a readable format to further troubleshoot the problem. It would help to compare the certificate we received with the actual that is on the server.
I already tried to use the openssl tooling to print the certificates. But the Java application is also using queues which seems to use different certificates than I was supplied and isn't easy to extract the queue certificates with the openssl tooling.
The above assumption was an incorrect assumption. I found the problem, we only supplied 1 ciphersuite on clientHello. One ciphersuite the server didn't support so that's why the handshaking failed:
11/9/2021 3:24:03 PMSession ID:  {}
11/9/2021 3:24:03 PMCipher Suites: [TLS_DHE_DSS_WITH_AES_256_CBC_SHA256]
11/9/2021 3:24:03 PMCompression Methods:  { 0 }
...
READ: TLSv1.2 Alert, length = 2
RECV TLSv1.2 ALERT:  fatal, handshake_failure
called closeSocket()
handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

But still the original question stands and would be useful for debugging.
sources:

*

*https://colinpaice.blog/2020/04/05/using-java-djavax-net-debug-to-examine-data-flows-including-tls/

*https://access.redhat.com/solutions/973783

*Using openssl to get the certificate from a server

*https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/ReadDebug.html

A: It is not possible to get the server certificate as pem with javax.net.debug You can try the following snippet which I also use for my own project:
Map<String, List<String>> certificates = CertificateUtils.getCertificateAsPem(
            "https://github.com/",
            "https://stackoverflow.com/");

It will extract all the certificates for the given urls in pem format. It is available within my own library which is publicly available here: GitHub - SSLContext Kickstart
Or you can also do the same with a CLI, see here: GitHub - Certificate Ripper Below is an example of the snippet above:
crip print -u=https://github.com -u=https://stackoverflow.com -f=pem

Please let me know if this is something which will do the trick for you

A: For the old stack (below 8u261 or 11) in all cases, and the new stack when the protocol used (negotiated) is TLS1.2 or below, javax.net.debug=ssl:handshake:packet will show you a 'raw write' for each outgoing record with (all) the data in hex and ASCII, and at least two 'raw read' for each incoming record (one for the header of 5 bytes, and one or more for the data) ditto. The fields going into an outgoing record are shown before the record, while the fields decoded from an incoming record are shown after it. For example on a connection to https://example.com after (build and) write the ClientHello and read (and decode) the ServerHello, I get for the Certificate message/record this pastebin (otherwise exceeds Stack size limit).
Take the body data (only) and on Unix, or WSL, run it through cut -c9-58 <hex | xxd -r -p >bin (for old stack -c7-56). The file bin now contains the Certificate message exactly as received: the first byte is 0B, the next three bytes are the (bigendian) length of the body of the message, the next three bytes are the length of the certificate list, and the next three are the length of the first certificate. To separate out that first certificate, do tail -c+11 bin | head -c$((0x$(xxd -p -s7 -l3 bin))) >cert1. You can now convert the cert to PEM with openssl x509 -inform d <cert1 or examine it with any other x509 options, or examine it with keytool -printcert -file cert1, or any other suitable tool. If you want (all or some of) the other cert(s) in the chain, it's a little more complicated.
TLS1.3, in new stack only, is slightly different. It encrypts the Certificate message and may have a hello-retry cycle, may have an early CCS, and will have an EncryptedExtensions message before the Certificate. Add :plaintext to the sysprop and for each incoming record you get a raw read of the header (5 bytes) in clear, a raw read of the body in cipher, and a decryption of the body, like this for the Certificate message/record.
This message differs slightly from the previous protocol version by having one byte of 00 between the message length and the certificate-list length, so change to: tail -c+12 bin | head -c$((0x$(xxd -p -s8 -l3 bin))).
Note some servers may combine messages in one handshake record (or encrypted handshake record), rather than using a separate record for each as example.com did, which will require a slight variation. If you have an example (accessible) of such, I will adjust.
However, I have no idea what you mean by 'queues' in an SSL/TLS connection, and why the much easier openssl s_client isn't usable. If you mean virtual hosting with the server choosing among multiple certificates using SNI, see the man page description of the -servername x option.


text:
Q: Is it possible to style a child element when hovering over the parent element? I would like to modify the styles of .childElement when .parentElement:hover is fired.
Something like this:

Is it possible?

A: I think you are looking for:
.parentElement:hover .childElement {
  display:block;
}

Note: CSS does not currently support nesting, however, it is planned. Currently, the proposed syntax is as follows:
.parentElement:hover {
  /* Note the ampersand (&) */
  & .childElement {
   display:block;
  }
}


text:
Q: How to mock com.google.common.collect.Iterators.partition() in Springboot? I am trying to write unit test for the below method "processStudentData".
@Override
public List<StudentsCSV> processStudentData(MappingIterator<Students> studentsMappingIterator, String studentDetails) {
    // ...

    Iterators.partition(studentsMappingIterator, BATCH_SIZE)
        .forEachRemaining(studentsList -> processBatch(studentDetails.getStudentId()));

    List<StudentsCSV> studentsCSVList = new ArrayList();
    // ...
    return studentsCSVList;
}

I have used com.google.common.collect.Iterators.partition() inside this method. And I tried to mock is as below, but it doesn't work. I want to know how to write unit tests for "processStudentData" method?
@EnableAutoConfiguration
@SpringBootTest
public class AudienceDataProcessorServiceTest {

    @Test
    void test(){
        List<Students>  studentsList = new ArrayList<>();
        Students student = new Students();
        studentsList.add(student);
        Iterator<Students> iteratorStudent = studentsList.iterator();

        Iterators iterators = mock(Iterators.class);
        when(iterators.partition(any(MappingIterator.class),anyInt())).thenReturn(Iterators.unmodifiableIterator(iteratorStudent));
    }
}


text:
Q: Where primitives data types are available in java? If they are not in class then where the data types are available under which package????How we are using them?
If they are comes under java.lang package then there should be some classes for them?
If they are built in so where are they?

A: they are built in in the language:
int, long, float, double, char, byte, boolean, short
For some comfort, such conversions, there are classes,too:
They all are in the java.lang package:
Integer, Long, Float, etc.
Examples:
int a = 3;
a++;

Integer aObj = new Integer(266666);

A: Read the specifications here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2

There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).

There is a third type as well named null:

There is also a special null type, the type of the expression null (§3.10.7, §15.8.1), which has no name.

Primitive types are special data types and not part of any package or class. Though there are related wrapper types e.g. Integer, Long, Boolean etc which are placed in java.lang package.

A: They are not class, and hence they does not exists in any package.
That's the design of Java.
Primitive types includes boolean, byte, char, short, int, long, float and double (I think I haven't missed any right? :P )
All of them have a corresponding wrapper under java.lang.  For example, Byte, Character, Integer etc.


text:
Q: Integrate Leaflet map into PDF I am current in the process of writing a thesis. Being in the field of GIS it obviously involves some maps ;). While the whole world switched to interactive online maps, Universities still require to hand in a PDF in the end. I am wondering if there are options to integrate a Leaflet map into a PDF. So basically I want to embed a HTML into a PDF.
I also asked a similar question here, but being a more GIS specific on GIS Stack Exchange.

A: You can embed html and run some javascript in PDF, but it appears that there is not enough support for Leaflet to run - there's no XmlHttpRequest which you would need to fetch your data. It might be possible with some hacking, since Adobe Javascript has its own net library, but it's not going to be easy.

A: I would suggest that you don't want to rely on anything dynamic for your thesis.
I would not link to a website and rely on that, and as much as possible, would ensure that the PDF stands on its own as a final document. Don't forget that (I think) you will be assessed on a bound version.
What I would do is set up your maps to be perfect for a print document, which means ensuring label fonts, map size, scale and all the marginalia are appropriate for print. That's your target. Then perhaps include an appendix or reference to support material that could include interactive mapping, that's just a bonus.
If you are really committed, there are ways you can do GIS-ish mapping in a PDF, and you can do 3D maps in a PDF. But it's not very standard and, I think, very gimmicky.

A: Your best bet is to take screenshots of the map, and cite the screen shots with a link to a live, working map. Be sure to put the map at some URL that won't change for a long time.
An interactive map is an external resource, and does not need to/should not be embedded or otherwise added to a print document. Cite it as you would any other resource not translatable to print, such as a movie.


text:
Q: Horizontal spacing between two canvas I have this horizontal space, that for the life of me; I cannot remove. It's to canvas in their own rows. I've tried multiple configurations, this is my most recent. Any ideas what I am doing wrong?

            <canvas id="gameHud"><

            <canvas id="worldMap">
             <textarea id="log" rows="20" cols="50"></textarea>

                    <button onclick="hostGame()">Host Game</button>
                     Host ID: <input id="hostID" type="text" readonly></input>
                     <button onclick="copyGameID()">Copy to Clipboard</button>

                    Host ID: <input id="joinHostID" type="text"></input>
                     <button onclick="join(document.getElementById('joinHostID').value)">Join Game</button>

                    <input id="chatInput" type="text" size="100"></input> <button onclick="sendMsg(document.getElementById('chatInput').value)">Say</button>

 Debug Options:
                     <input type="checkbox" id="green" checked>
                     Green
                     <input type="checkbox" id="red">
                     Red
                     <input type="checkbox" id="blue">
                     Blue

                     <input type="checkbox" id="debugMode" onclick="toggleDebug();" checked>
                     Show Grid


text:
Q: How to lock levels in Android app I am developing a quiz application in Android. In my application I'm having categories and I added levels in each category.
Now I need to lock all the categories except the first one. The user will be able to unlock the Categories only after he/she completes the specific goal of the level. I don't know how to lock categories in Android. Categories are in the form of buttons. By using the following I'm populating the list and passing of three categories, i.e. Hollywood, Bollywood and Music.
hollywood = (Button) findViewById(R.id.main_hollywood);
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
            "Font/game_font.ttf");
    hollywood.setTypeface(tf);
    OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            settings.edit().putBoolean("check", false).commit();
            Intent intent = new Intent(getContext(), SceneActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(intent);
            finish();
        }
    };
    hollywood.setOnClickListener(listener);

    bollywood = (Button) findViewById(R.id.main_bollywood);
    tf = Typeface.createFromAsset(getContext().getAssets(),
            "Font/game_font.ttf");
    bollywood.setTypeface(tf);
    listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            settings.edit().putBoolean("check", false).commit();
            Intent intent = new Intent(getContext(), SceneActivity1.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(intent);
            finish();
        }
    };
    bollywood.setOnClickListener(listener);
    music = (Button) findViewById(R.id.main_music);
    tf = Typeface.createFromAsset(getContext().getAssets(),
            "Font/game_font.ttf");
    music.setTypeface(tf);
    listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            settings.edit().putBoolean("check", false).commit();
            Intent intent = new Intent(getContext(), SceneActivity2.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(intent);
            finish();
        }
    };
    music.setOnClickListener(listener);

}

A: There are two methods to solve this

*

*Use shared preference in your application where you can handle the situation onlick

*Use sqlite database and update the column appropriately
Let me know if you need further information
For shared preference you can use TinyDb
This class simplifies calls to SharedPreferences in a line of code. It can also do more like: saving a list of strings, integers and saving images. All in 1 line of code!
Example usage:
    TinyDB tinydb = new TinyDB(context);

    tinydb.putInt("clickCount", 2);
    tinydb.putFloat("xPoint", 3.6f);
     tinydb.putLong("userCount", 39832L);

    tinydb.putString("userName", "john");
    tinydb.putBoolean("isUserMale", true);

    tinydb.putList("MyUsers", mUsersArray);
    tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

//These plus the corresponding get methods are all included
This is just an example of how easy it is to use. There are many more usefull methods included in the class. Enjoy :)


text:
Q: Scroll problem in tableview in iphone I am showing some records in tableview. I am seeing vertical scroll is coming on screen but whenever I am clicking for scroll I am getting an SIGABRT error in main() function.
Why this error is coming ?
Thanks
Here are the code which is adding text in table view. This is written in viewdidload() function.
-(void) viewDidload() {

    extern NSArray *wallvalue;

     tableList = [[NSMutableArray alloc] initWithCapacity:[wallvalue count]];
    for (NSDictionary *person in wallvalue) {
        NSString *personName = [person objectForKey:@"message"];

      if(![[NSNull null] isEqual:personName] && [personName length])
        {
            [tableList addObject:personName];
              NSLog(personName);
        }
    }

}

And my error is occuring in main function which is below.
int main(int argc, char *argv[])

{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    int retVal = UIApplicationMain(argc, argv, nil, nil);

    [pool release];

    return retVal;

}

Error is : Thread EXC_BAD_ACCESS in line (int retval= UIApplicationMain(argc, argv, nil, nil);

A: My guess is your numberOfRowsinsection is more than what your having modal(data).while your trying to scroll the last objects will load in the cells through
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  method.
so once check your data while loading the cells once again.while your scrolling  below method will always call
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


text:
Q: Invalid postback or callback argument. Event validation requires unnecessary "using System.Web.UI" I have a page with a bunch of text inputs, dropdowns, and buttons. All manipulation of the inputs is done server side. Javascript only adds event listeners which manipulate the contents of the text inputs.
When I remove the unnecessary (dimmed)

using System.Web.UI

I get the annoying "Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation=\"true\"/> in configuration or <%@ Page EnableEventValidation=\"true\" %> in a page.  ...
When I put it back in the problem goes away.

Removing javascript and all processing in Page_Load does not make the problem go away.
How weird is that? What is going on here?

A: Turns out it was caused by a line break in a <asp:ListItem>Big long item
with a line break</asp:ListItem>.
Presumably, when the item with the line break was selected, the returned HTML no longer matched the source (since line breaks are converted to a space character).


text:
Q: Using a BASH integer variable in an awk command I'm trying to run a command on every entry in a line of text:
#! /bin/bash

range=$(ls -s /home/user/Pictures/Wallpapers | wc -l)

for (( i=0; i<$range; i++ ))
do
   d=$(ls /home/user/Pictures/Wallpapers | paste -sd " " | awk -F' ' '{ print $i }')
echo $d
done

But when I run it, it simply prints out the entire line of file entries with every iteration of the loop. I think it's because the "i" is not being interpreted since it's technically in between single quotes, and I can't figure out how to prevent it from doing this.
Thanks.

A: You can pass variables to awk with -v argument like in:
d=$(ls /home/user/Pictures/Wallpapers | paste -sd " " | awk -v var="$i" -F' ' '{ print var }')

A: To print the names of files in a directory repeated as many times as there are files in the directory, you can use:
for x /home/user/Pictures/Wallpapers/*; do
   ls /home/user/Pictures/Wallpapers/
done

or
for x /home/user/Pictures/Wallpapers/*; do
  for y /home/user/Pictures/Wallpapers/*; do
    echo $x
  done
done

A: for f in /home/user/Pictures/Wallpapers/*; do echo $f; done


text:
Q: How to include Tag names in AEM search query builder while Tag IDs are saved in the repository In AEM, how can we write a query as the default search works, where a Tag ID is saved for an asset, while the user wanted to search by the Tag Name/jcr:title?
For example, we can search for assets that has a particular Tag assigned. As below:

the way there are assigned is as follows:

And are saved in the repository as ID's.. as below:

For example, a tag hierarchy:
TAG ID:
/etc/tags/SXM/shows/entertainment/kids/8216/1073743514

The TAG NAME for the above:
SXM > Shows > Talk > Kids > Kids Place Live > Weird Al April

I tried the below but does not work?
type=dam:Assets
path=/content/dam/
tagsearch=SXM:Shows/Talk/Kids/Kids Place Live/Weird Al April

A: I was able to resolve this and posting the answer.
There is a predicate tagsearch that would build the tag hierarchy to the search query.
The below worked for me:
type=dam:Assets
path=/content/dam/
tagsearch=Weird Al April

or
type=dam:Assets
path=/content/dam/
tagsearch=Kids Place Live

or
type=dam:Assets
path=/content/dam/
tagsearch=Kids


text:
Q: Why was my "SO answering workflow" question closed? How could I rephrase it? Question in question: What is your SO answering "workflow"?
Since this was closed, I guess I don't quite get what belongs/doesn't belong on meta. I'm asking so that I hopefully don't ask a bad question here again, and because I'm not sure how much the "closed as not constructive" comment applies in this case.
It was closed as not a good fit, but I guess I don't see why not. SO has a lot of little details; what better way for a new user to see how to approach the site than to have him/her see how established users do it?

A: Posts on Meta have a lot of leeway; a lot of the things that normally wouldn't be allowed on the main site are allowed on Meta, as long (not always) as it's in the pursuit of advancing the site in some way.
However, your question didn't help to advance the site (the main site or meta) in any way, you simply asked what people's workflow is on the main site.
The question could possibly be constructive (I'll be honest, I'm giving it the benefit of the doubt, right now, I don't really see how), but as it stands right now, it's just an open call for people to describe how they interact with the site.  Even for meta, that's not a good fit for the site.  A gazillion people will answer and there's no way to come to a consensus about which approach is the best using the system in place.


text:
Q: How to download files from a database, and get them as image in Asp.net core MVC? I have been reading and working around downloading and uploading files to database! I just made upload work, so now i save my files in Binary in the database! Also i display the name in the View :
@model IEnumerable<RH_Files>

                    @Html.DisplayNameFor(p => p.Name)

            @foreach (var item in Model)
            {

                      @Html.DisplayFor(model => item.Name)

            }

as you can see :

my model:
 public class RH_Files
    {
        [Key]
        public int id { get; set; }
        public string Name { get; set; }
        public string ContentType { get; set; }
        public Byte[] Data { get; set; }
    }

Now what i need, is to have a download button for each item, that will trigger a c# action that downloads the file selected...
Any help is appreciated!!

A: in your controller:
public FileResult Download(int id)
{
      var fileToRetrieve = db.GetFile(id);
      return File(fileToRetrieve.Data, fileToRetrieve.ContentType);
}


text:
Q: Passing multiple value for a parameter in my sql I have written a query below:
SET @City = 'London,Lyon,Kln';
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@City, ',',@r:=@r+1),',',-1) City
FROM (SELECT @r:=0) x,
(SELECT 'x' xx
    UNION
    SELECT 'v' xx
    UNION
    SELECT 'z' xx) z;

Which returns Cities in table format & now i want to pass it as a parameter to a query like  :
SET @City = 'London,Lyon,Kln';
SELECT *
FROM Invoices
WHERE City IN (
    SELECT SUBSTRING_INDEX(
        SUBSTRING_INDEX( @City, ',',@r:=@r+1),',',-1
    ) City
    FROM (SELECT @r:=0) x,
    (SELECT 'x' xx
        UNION
        SELECT 'v' xx
        UNION
        SELECT 'z' xx) z
)

But when I execute this query it returns the records for 'Kln' city only, ie. for last city mentioned in @City variable.
So please tell me how to get the records for all cities of @City variable.


text:
Q: Not getting param into bottomTabNavigator I have login screen. I want to pass params/user) to my 2nd screen with 2 tabs in it. I don't know why but somehow I don't get params in my 2nd screen. I have custom header and there params is working perfectly.
App.js code:
const Routes = createStackNavigator(
  {
    Login: {
      screen: Login,

      navigationOptions: ({ navigation }) => ({
          header: null,
        }),

    },
    Main: {
      screen: MainScreenRoutes,

      navigationOptions: ({ navigation }) => ({
          header: null,
        }),
    },
});

How I navigate to Main from Login:
this.props.navigation.navigate("Main",{user: JSON.stringify(obj)});

My main routes:
let headerDefaultHomeNavigationConfig = {
  header: props => <CustomHeaderMain {...props} />,
  ...HeaderStyles
};

let headerDefaultNavigationConfig = {
  header: props => <CustomHeader {...props} />,
  ...HeaderStyles
};

const Tab1 = createStackNavigator(
  {
    Domov: {
      screen: HomeScreen,
    },
  },
  {
     navigationOptions: ({ navigation }) => ({
       ...headerDefaultHomeNavigationConfig
      })
  }
);

const Tab2 = createStackNavigator(
  {
    Dnevnik: {
      screen: Diary,

    }
  },
  {
    navigationOptions: ({ navigation }) => ({
      ...headerDefaultNavigationConfig
    }),

  }
);

const bottomTabs = createBottomTabNavigator(
{
  Domov: Tab1,
  Dnevnik: Tab2,
},
{
  initialRouteName: "Domov",
  navigationOptions: ({ navigation }) => ({
      //header: null,
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === 'Domov') {
          //iconName = `home${focused ? '' : '-outline'}`;
          iconName='home';
        } else if (routeName === 'Dnevnik') {
          //iconName = `ios-calendar${focused ? '' : '-outline'}`;
          iconName='ios-calendar';
        }

        // if focused return view with line
        if(focused) {
          return (
            <View style={styles.item}>
                <Icon name={iconName} style={{fontSize: 20, color: '#FFF'}} />
                <View style={styles.line}></View>
            </View>
          );
        } else {
          return(
            <Icon name={iconName} style={{fontSize: 20, color: '#FFF'}} />
          )
        }

      },

    }),
    tabBarPosition: 'bottom',
    tabBarOptions: {
      activeTintColor: 'white',
      showLabel: false,
      inactiveTintColor: '#4C2601',
      style: {
        backgroundColor: '#033D51',
      },
      labelStyle: {
        fontSize: 12,
        lineHeight: 30,
      },
    },
    swipeEnabled: true,

});

My HomeScreen constuctor:
export default class HomeScreen extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            user: this.retrieveItem('user'),
        }

        alert(JSON.stringify(this.props.navigation.state));

    }

In my 'Domov' screen I don't get my params, but in header there is params.
It looks like there is problem with navigation. I navigate to MAIN which is createbottomnavigation. And there I cannot get params...
If I changed my createbottomnavigation with this;
const bottomTabs = createBottomTabNavigator(
{
  Domov: HomeScreen,
  Dnevnik: Tab2,
},
);

Than I'm getting params to that screen. It looks like that stacknavigator canceled my params

A: You should be getting it, in your Login page, how do you receive your params?
It should be done like this:
const {params} = this.props.navigation.state
console.log(params.user)


text:
Q: Constraint violation with @OrderColumn in @ManyToMany I get a violation of a primary key constraint of the join table, that is automatically created by EclipseLink for the following classes:
@Entity public class Link {
    @ManyToMany @OrderColumn
    private List<Node> nodes; ...

@Entity public class Node {
    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "nodes")
    private List<Link> links; ...

The violation occurrs, if I insert a Link with the same Node on first and second position of it's nodes. Indeed there is a generated index with NODES_ID and LINKS_ID (missing NODES_ORDER). How could I influence EclipseLink or other Providers in order to ommit or extend this constraint?
Using: Glassfish 4.1.1, EclipseLink 2.6.4 or 2.7.0 (cross post), Java 8

A: Try adding this:
@org.hibernate.annotations.ForeignKey( name = "none")

on both sides of the mapping.


text:
Q: Reload entire page except the User Control My application has one master page and 5 child page to load inside it.
Contents of Master Page:
1. UserControl (Drop Down)
2. 5 Main Tabs (Child Page loads for every Main Tab Click).
Initially when application loads, all the data is loaded for Drop Down and one of the child page .
so whenever a click on one of the main tab link (its href),so whole page gets reloaded and data will be loaded again for all the controls of the page.
so , i don't want to load the data for my drop down again and again on every Main Tab Click.
As i am working on legacy application every thing is coded, i can't use Update panel for this as a solution because it requires lot of code change.
so i am looking for a solution to keep my Drop Down Data static across all the tabs, even if it refreshes for every tab click.

A: Why not hide the information in a div and display only each div when its clicked?
...this will keep the links static and only navigate between the pages.
Put all the code on one page:
CSS:
#content > div {
    display: none;
}

#content > div:target {
    display: block;
}

HTML:

Page 1

Page 2

Page 3

Page X

Let me know how you get on :)
Good Luck

A: IMO you need to use a common place to store your data , you may use session
fill the session with data on app start -- now on every page refresh / page load keep a check if session has data don't bind the drop down (in user control).


text:
Q: Django: Javascript error with alert box displaying values I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is that my Javascript is not printing the correct values. In both spots, it says undefined. I will put a picture below for reference.
views.py
def inventory(request):
    products = request.POST.getlist('products')
    for product in products:
        a = Post.objects.get(title=product)
        a.quantity = a.quantity -1
        a.save()
    print(products)
    return redirect('blog-home')

home.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
    <form action="{% url 'js' %}" method="POST" id="menuForm">
      {% for post in posts %}
        {% if post.quantity > 0 %}

                  {{ post.category }}

{{ post.title }}

 Price: ${{ post.Price }}

 Sale: ${{ post.Sale }}

                <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
              </input>

        {% else %}
        {% endif %}
      {% endfor %}
      <button id="btn" type="submit" form="menuForm">Confirm Purchase</button>
    </form>

{% endblock content %}

javascript.js
function getSelectedCheckboxValues(name) {
    const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
    let values = [];
    checkboxes.forEach((checkbox) => {
        values.push(checkbox.value);
    });
    return values, tPrice;

var price = 0;
var tPrice =0;
if (values=='Milk'){
    var MPrice = 3.99
    tPrice = price+MPrice;
}
if (values == 'Cheese'){
    var CPrice = 4.50
    tPrice = price + CPrice;
}
if (values == 'Yogurt'){
    var YPrice = 1.99
    tPrice = price + YPrice;
}
}

const btn = document.querySelector('#btn');
btn.addEventListener('click', (event) => {
    alert('You ordered: ' + getSelectedCheckboxValues('products')+
        '\nTotal Price: $'+ getSelectedCheckboxValues('tPrice'));
});

A: First of all you are passing the parameter to the function getSelectedCheckboxValues as a string when you call them in the alert which is completely wrong.
Also you are directly comparing values list with strings which is not possible. You need to loop over the list and then compare the different elements with the different products. I will also recommend to create an object instead of the list and keep the product name as key and its price as value.


text:
Q: Not allowed to return a result set from a trigger I have problem:
I created procedure :
CREATE PROCEDURE `tran_sp` ()
BEGIN
  SELECT 'procedure runned!';
END
$

It's works !
mysql> CALL tran_sp()$
+-------------------+
| procedure runned! |
+-------------------+
| procedure runned! |
+-------------------+
1 row in set (0.00 sec)

Then i created trigger :
mysql> CREATE TRIGGER my_trigger1
    ->     AFTER INSERT ON users
    ->     FOR EACH ROW
    -> BEGIN
    ->          CALL tran_sp();
    -> END$

mysql> INSERT INTO users VALUES(166,156)$

ERROR 1415 (0A000): Not allowed to return a result set from a trigger
mysql>
Help me please.

A: The exception is I think clear enough.
You can perform additional operations inside a trigger (call a SP, perform insert / update / delete operations, ...) but all of those aren't allowed to return any result.
This means, a SP with a simple select-statement inside isn't allowed. If instead you would use this select statement within a loop for instance in order to perform updates or similar, this would be allowed, as you wouldn't return anything.
The reason is, that an insert/update/delete statement can't return anything, it can't return the result set of your stored procedure and therefor you shouldn't try to return one inside the trigger.


text:
Q: Delete function not working properly in angular? this is my code for delete particular row in table on form in angular.
its working but not properly. Problem is when i click on delete button
only pop ups comes.after that nothing happens. when i refresh my page
on refresh that particular row deletes.
So everytime i have to refresh
page to see delete works or not?  How to solve this issue so i dont
have to refresh my page evertytime after delete something.
<a ng-click="deleteInfo(detail)" onclick="return confirm('Are you sure
 you wish to delete this Record?');">

A: it's because only your onclick triggered in this scenario, you should use a custom directive to achieve this, like :
module.directive( "mwConfirmClick", [
  function( ) {
    return {
      priority: -1,
      restrict: 'A',
      scope: { confirmFunction: "&mwConfirmClick" },
      link: function( scope, element, attrs ){
        element.bind( 'click', function( e ){
          // message defaults to "Are you sure?"
          var message = attrs.mwConfirmClickMessage ? attrs.mwConfirmClickMessage : "Are you sure?";
          // confirm() requires jQuery
          if( confirm( message ) ) {
            scope.confirmFunction();
          }
        });
      }
    }
  }
]);

please refere to this old post

A: Use sweet-alert for confirmation except "onclick" method

http://t4t5.github.io/sweetalert/

A: You can write your confirm alert inside the ng-click function.
scope.deleteInfo = function(detail){
  $ngBootbox.confirm('Are you sure you wish to delete this Record?')
 .then(function() {
     //either you can reload window or delete the particular ng-model or whatever
  },
   function() {
   });
return false;
}


text:
Q: PHP mb_strpos fails for Greek strings I have a file browser and I'm trying to find which file names contain a given query.The code goes like this:
$query = (isset($_POST['s']))? mb_strtolower($_POST['s'],'UTF-8') : '';
$res = opendir($dir);
    while(false!== ($file = readdir($res))) {
if(mb_strpos(mb_strtolower($file,'UTF-8'),mb_strtolower($query,'UTF-8'),0,'UTF-8')!== false) {
    echo $file;
}}

For English words this works fine,but when the text  is in Greek,the results are not as expected,meaning that it works for some but not all of Greek words.Could anyone help me solve this?

A: The graphemes may render the same or similar but they are not represented the same way. For example:

*

*ά is represented here as Unicode Character 'GREEK SMALL LETTER ALPHA WITH TONOS' (U+03AC)

*ά is represented here as Unicode Character 'GREEK SMALL LETTER ALPHA' (U+03B1) followed by Unicode Character 'COMBINING ACUTE ACCENT' (U+0301)
These were copied directly from your comment.

In order to compare them you should first use normalizer_normalize() on both strings to obtain them in their normalized forms. Which type of normalization form to use is ultimately up to you. There are four:

*

*NFD (Canonical Decomposition)

*NFC (Canonical Decomposition, followed by Canonical Composition)

*NFKD (Compatibility Decomposition)

*NFKC (Compatibility Decomposition, followed by Canonical Composition)

Because this normalization is being used completely internally just ignore NFC and NFKC, there's no need to recompose. This leaves you with the option of either NFD or NFKD - canonical or compatible. The names give you a bit of a clue on how strict they are regarding equivalence.

1.1 Canonical and Compatibility Equivalence:

Canonical equivalence is a fundamental equivalency between characters or sequences of characters that represent the same abstract character, and when correctly displayed should always have the same visual appearance and behavior.

Compatibility equivalence is a weaker equivalence between characters or sequences of characters that represent the same abstract character, but may have a different visual appearance or behavior.

For searching I would go with the latter.
Example:
$foo = "παράρτημα";
$bar = "παράρτημα";
var_dump($foo === $bar);
var_dump(
    normalizer_normalize($foo, Normalizer::FORM_KD) ===
    normalizer_normalize($bar, Normalizer::FORM_KD)
);

Output:
bool(false)
bool(true)


text:
Q: Checking for strict mode compatibility in Javascript before invoking it I am curious if there is anything wrong with the following code meant to test for Javascript strict mode compatibility before invoking it:
(function() { "use strict"; return this; })() || "use strict";

I'm worried it is either too bulky or won't actually work for some reason.
Update
Robert answer my question below very well. I thought I would put this here for future reference for other's benefit. From John Resig's "ECMAScript 5 Strict Mode, JSON, and More":

[T]he syntax that's used to enable strict mode...[is] simply a string in a single statement that happens to contain the contents "use strict". No new syntax is introduced in order to enable strict mode. This is huge. This means that you can turn strict mode on in your scripts – today – and it'll have, at worst, no side effect in old browsers.

A: The check won't work, and isn't needed. If the browser doesn't support strict mode, it'll simply treat the strict mode declaration as a string literal expression, which is a completely valid expression and has no side effects.
Just use the declaration directly when strict mode is desired in those browsers that support it.
In any case, the strict mode declaration is required to stand on its own, and not be part of a larger expression, otherwise even modern browsers that have strict mode support will see it as a common meaningless string literal.


text:
Q: C# How to retrieve a certain text located within a string? Does anyone know how to retrieve a short sentence from within the main string? Is it required to use regular expressions?
I am trying to retrieve the text "Thu Dec  9 05:12:42 2010" which is the time from the main string "LastWrite Time Thu Dec  9 05:12:42 2010 (UTC)" which is after "Time" and before "(UTC)".
I am also new to C# so sorry for the simple question.
May someones please advise or show some C# methods that may be used to retrieved the text? Thanks!

A: You can use a regular expression:
Match match = Regex.Match(text, @"Time (.*?)\(UTC\)");

You can then get the substring you want from match.Groups[1].Value.

A: Look into using the System.String.Substring and System.String.Length methods.
var logTime = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";
logTime = logTime.Substring("LastWrite Time ".Length);
logTime = logTime.Substring(0, logTime.Length - " (UTC)".Length);

This should get you close to what you're looking for.

A: You could use regular expressions (regex) but they are hard to understand. Most people consider them difficult to create unless you are very used to them. In case you are familliar with regular expressions, you can study the Regex class that handles regex in C#.
However what you try to do is also possible using usual methods on the String class. Look into it and see what methods you can use.
Mainly your logic using the string class' methods would be to determine if you have some  pattern in your sentences. Try to find common elements that surround the data/time string you want to extract (begin and end). Then use the Substring(...) method. or other methods. It can be done in multiple ways.

A: Following code should give you what you want. It is not a flexible solution and will work only for this scenario:
String value = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";

String newValue = value.Replace("LastWrite Time", "").Replace("(UTC)", "").Trim();

For more flexibility, use Regular Expressions.

A: try this out,
If your text is in only in string variable, you can use SubString() method to retrieve the string.
Ex:

String str = "LastWrite Time Thu Dec 9
  05:12:42 2010 (UTC)";
  str.substring(15,23);

will return you Thu Dec 9 05:12:42 2010 as result.

A: Your problem is essentially string parsing.
The easiest way is to just use the IndexOf and Substring methods on the string itself. This will only work for very simple scenarios. Just remember, the string is immutable and those functions will always return new strings, never modify the original.
The next level up is to use regular expressions, this will handle slightly more complex scenarios.
The best way is to use a full lexical analysis tool, which is probably overkill for the scenario you presented above. Would still be worth looking into just for fun.

A: This is a rather common problem so you should extend the string class with a flexible "Between" method.
First you´ll have to define a extension class:
public static class StringExtensions
{
    /// <summary>
    /// Returnes a substring located between a leading substring (head) and following substring(tail).
    /// Return null if head or tail are not part of this string.
    /// </summary>
    /// <param name="mainString"></param>
    /// <param name="head">leading substring</param>
    /// <param name="tail">following substring</param>
    /// <returns>ubstring located between head and tail</returns>
    public static String Between(this string mainString, string head, string tail)
    {
        int HeadPosition;
        int TailPosition;
        int ResultPosition;
        int ResultLenght;
        //test if mainstring contains head and tail
        if (!mainString.Contains(head) && mainString.Contains(tail))
        {
            return null;
        }
        HeadPosition = mainString.IndexOf(head);
        TailPosition = mainString.IndexOf(tail);
        ResultPosition = HeadPosition + head.Length;
        ResultLenght = TailPosition - ResultPosition;

        return mainString.Substring(ResultPosition, ResultLenght);
    }
}

Then all you have to do is call the new method on any string.
var logTime = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";
logTime = logTime.Between("Time","(UTC)").Trim();

Please note that "Between" will only be accessible if you use the namespace that you defined StringExtensions in.


text:
Q: Создание собственной аутентификации Есть таблица Users, в ней [id, login, password, level]
Что можно придумать для авторизации пользователя, чтобы в дальнейшем проверять его level где нибудь во вьюхе ? Ну и соответственно в зависимости от level выводить ему какие либо данные.
Пытался сделать это через session, так session недоступен из модели.
На пример, где нибудь во вьюхе:
<% if Auth::User.is_auth? %>

 Авторизирован, логин: <%= Auth::User.login

<% end %>

A: Если хотите разобраться - двигайтесь по этому руководству например + видео скринкасты там тоже есть как про аутентификацию и про многое другое.
А после своей реализации посмотрите на gem devise и используйте его (при нужде после форка на гитхабе сможете его "улучшить", хотя это маловероятно).


text:
Q: how to update redux state using immutability helper? I am trying to update my redux crud form.I am using with the help of immutatbility helper.
My reducer is:
case UPDATE_TODO:
console.log("reducer todo",action.toDo,state)
return update(state, { $set: [action.toDo] })

But instead of replacing specific object it replace whole array into one.Where I am doing wrong??
My State is this:
[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]

and after updating it should be like this:
[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]

but instead its giving result this:
[
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]

A: Your code is not targeting the specific todo you want to update in state, hence it replaces the whole state. There are two ways you can achieve this:
1) Find the index of the todo item you want to update using Array.findIndex method before using $set method.
const todoIndex = state.findIndex(todo => todo.id === action.toDo.id)
const newState = update(state, {[todoIndex]: {$set: action.todDo }})
2) Find the index of the todo item you want as (1) above and then use $splice method.
const todoIndex = state.findIndex(todo => todo.id === action.toDo.id)
const newState = update(state, {$splice: [[todoIndex,1,action.todDo]]})


text:
Q: Layout with same behaviour as gridview? I would like to know if there is a layout with a behavior similar to GridView or a trick to do the following thing :
I have a few elements displayed in a row, but I would like to elements to get to the next line if the size of the screen is too small. To illustrate my problem :

The red rectangle being the portview of the device

A: Try this library. There is no component that does what you are asking natively, but people have written such components.
https://github.com/blazsolar/FlowLayout
Hope this helps

A: I didnt try that be4 but i think you can do this programmatically
You need to check the elements count and calculate their width (including spaces between them) then check if you add the new element width with the Parent Width if can hold it then add
if not then the new element top = the last row top+the last row height
and the new element left = the first element at the last row left
try it and if u need any help to do it i can try to code it for you


text:
Q: Circular view path I am using Spring MVC 3 and all I am trying to do is submitting a form with post request and redirecting the post request handler on the controller to some page. But I am getting the following error when I try to do that:
javax.servlet.ServletException: Circular view path [thanks.htm]: would dispatch back to the current handler URL [/wickedlysmart/thanks.htm] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

Following is the code I am using:
Request handler:
@RequestMapping(method=RequestMethod.GET, value="thanks")
public ModelAndView thanks() {
    logger.debug("redirecting..");
    return new ModelAndView("thanks");
}
@RequestMapping(method = RequestMethod.POST, value="talk")
public String processContactForm(HttpServletRequest req) {
    //...
    return "redirect:thanks";
}

View resolver in spring application context:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix" value="" />
    <property name="suffix" value=".htm" />

</bean>

I am not quite able to understand what is going on here. I see "redirecting.." being logged and then I get this error. Could someone help me with this issue?
Thanks.

A: Following solved the problem:
@RequestMapping(method=RequestMethod.GET, value="captured")
public ModelAndView thanks() {
    logger.debug("redirecting..");
    return new ModelAndView("thanks");
}
@RequestMapping(method = RequestMethod.POST, value="talk")
public String processContactForm(HttpServletRequest req) {
    //...
    return "redirect:captured";
}

As you could see, I just changed the redirect from "thanks" to "captured" and modified the "value" for the redirect request handler from "thanks" to "captured" as well and it worked. Thanks.


text:
Q: Refresh/reload textview from database | Button Tapped Function I have declare the textview outlet:
@IBOutlet weak var messageView: UITextView!

I have created the interface action, and place the logic:
@IBAction func refreshTextViewTapped(sender: UIButton) {

// logic

}

Reload/update textview with new content.

A: doesn't the setText function automatically update the textview? What would you need a reload function to do if the text is already being updated?
- (void)viewDidLoad()
{
    setMyTextView();

    // create the button that calls your function to update the text view
    UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 44);
    [myButton addTarget:self action:@selector(setMyTextView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myButton];
}

- (void)setMyTextView()
{
    NSString *myText = // value that is returned from the database query;
    [self.myTextView setText:myText];
}


text:
Q: How do I check whether or not a property is true in an array of objects? I am trying to print an image only if the HD property in the object is set to true. I am also trying to the get the number assigned to an element and print an image that many times. (To different functions).
var movies = {
    "movies": [{
        "title": "Blue Streak",
        "year": 1999,
        "starring": "Martin Lawrence, Luke Wilson",
        "HD": true,
        "description": "Blue Streak is a 1999 American buddy cop comedy film directed by Les Mayfield and starring Martin Lawrence, Luke Wilson, Dave Chappelle, Peter Greene, Nicole Ari Parker and William Forsythe. The film was shot on location in California. The prime shooting spot was Sony Pictures Studios which is located in Culver City, California.",
        "photo": "data/blue-Streak.jpg",
        "rating": 4
    }

So for every movie where HD is set to true I want to show an image. Also for the rating, I want to show that many stars. The function I tried have not worked. Please help!

A: Your loop should look something like...
for (var i = 0; i < movies.movies.length; i++){
    if(movies.movies[i].HD === true){
        var src = 'images/' + movies.movies[i].photo;
        $(".hd").append("<img src='" + src + "'");
    }

}

if you want to append your image to every element with a class of hd on your page.  With that you should be able to figure out how to get to your star rating, just like the HD or photo property, and then figure out what logic you need to add to put in to have your stars show up. I'd think about just adding the number as a class to the image, and then have a div after the image that gets styled based on a img with the number class with an adjacent sibling selector to access that next div.


text:
Q: Jackson - Deserialize array as String Is there a way to deserialize this:
public List<CustomeObject> list;

to a String like this:
"[{first_custome_object}, {second_custome_object}]"

When I'm trying to do so I get "There was a problem when sending the request.
    org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token"
Can I "force" this list to be deserialized to a string?


text:
Q: Honeycomb makes texts pixelized My app looks fine on my Galaxy S, but when I run it on a Galaxy Tab 10.1 (Android 3.0), the texts look pixelized/smeared:

The XML used for the Synchronize button follows:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/synchronizeButton"
    android:background="@drawable/button"
    android:text="Synchronize"
    android:textSize="20dp"
    android:textColor="@drawable/buttoncolors"
    android:layout_marginBottom="10dp"/>

Is there something wrong I am doing, or is there something special I need to do to make my apps Honeycomb-compatible?

A: Is your application running in compatibility mode? If so, this is expected. You need to indicate in your manifest that you support large screens.

A: Try changing textSize="20dp" to textSize="20sp".  When dealing with text you should always use "sp" (scale-independent pixel).  Hopefully this fixes it.
see this page for more info: http://developer.android.com/guide/practices/screens_support.html


text:
Q: How to change the style of layout elements for each specific page? I have a Nuxt.js and Vue.js project and I have a layout in it that all my landing pages use this layout and I have given a series of styles to the v-app-bar menu tag in this layout. But as you can see in the image on the brokers page, the styles are displayed correctly for the nav-bar section , This means that the nav-bar menu buttons are white in color,
But on the how it work page, the color of the menus should not be white and should be changed to black so that the menus can be easily viewed.
How it works page:
Brokers page:
The main How it works page, which should be designed in the same way:
My Code is:
<v-app-bar absolute color="transparent" elevate-on-scroll>
<div class="d-flex align-center">
    <v-img max-width="166"lass="d-flex align-center mr-10" src="/RectangleProfile.png">
    </v-img>
    <v-btn nuxt to="/landing-page/how-it-works" text
     class="mr-2 font-bold-link-text">
       How it Works
    </v-btn>
    <v-btn
     text
     class="mr-2 font-bold-link-text"
     nuxt
     to="/landing-page/list-of-top-brokers"
  >Brokers</v-btn >
  <v-btn text class="mr-2 font-bold-link-text">Tutorial</v-btn>
  <v-btn text class="mr-2 font-bold-link-text">Blogs</v-btn>
  <v-btn text class="mr-2 font-bold-link-text">About us</v-btn>
  <v-btn
     v-if="selectedMagnify === false" icon
     v-on:click.stop="searchSelected()">
    <v-icon color="white">
        mdi-magnify
    </v-icon>
 </v-btn>

 <v-text-field
    v-else
    flat
    color="#ffffff"
    autofocus
    hide-details
    rounded
    height="40"
    filled
    dense
    single-line
    clearable
    placeholder="Search">
 </v-text-field>
</div>
</v-app-bar>

My CSS Code is:
.font-bold-link-text {
  font-weight: normal;
  font-size: 14px;
  color: #ffffff !important;
}

A: As Iman said in the comments, you can use a scoped style on the page where you have the problem.
Otherwise, another way is to create a dark class that is bind to a var. And you set it to true on the page where you need the black buttons. That way, you can have your style in a global stylesheet.
Something like :

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<v-btn text class="mr-2 font-bold-link-text">Light button</v-btn>
<v-btn text class="mr-2 font-bold-link-text" :class="dark: dark">Dark button</v-btn>
<script>
export default {
  data(){
  return{
    dark: true,
  }
  },
}
</script>
<style scoped>
.font-bold-link-text{
  padding: 8px 16px;
  color: black;
  background: white;
}
.dark{
  padding: 8px 16px;
  color: white;
  background: black;
}
</style>


text:
Q: How good is Monte Carlo Simulation when the variable distribution is unknown? I am reading the book "how to measure everything", there is a chapter when the author encourages the usage of Monte Carlo simulation in simulating the future events in order to get a better understanding of the risk/ uncertainty involved. The theory sounds great in paper, and I am tempted to apply Monte Carlo techniques to startup analysis, to study the performance of employees, sales campaign, markets... everything!
But in practice, I doubt whether Monte Carlo simulation is useful when the distribution of the variables involved in an equation is unknown. Think of the stock price return distribution-- it doesn't fit into a Gaussian Distribution, but what distribution we can use? And when the variable distribution is unknown, how useful is Monte Carlo simulation? My guess is not very useful, but I am right?
A relevant, but probably narrower question is, is there any research done along the line of sensitivity analysis? By "sensitivity analysis" I mean we assume known distributions for the variables, but we perturb them a little by slightly changing the distribution shape or slightly changing some of the constants, will the outcome of the simulation results remain roughly the same, or completely different?

A: In practice simulation is almost always done without full certainty about the distribution.
For example, one might consider a lognormal distribution for some random variable... but what if it was a little lighter tailed (gamma, say)? Or heavier tailed (inverse gamma, say)? Or much heavier tailed (inverse Gaussian, say)? Or log-t?
What if it was some mixture of lognormals? ... or perhaps some form of regime switching?
What if there was a slight dependence in the data?
One can consider a host of ways in which the model may  be inadequate (preferably springing from an understanding of the process being dealt with), and see via simulation how that affects the conclusions.
Such things are commonplace. It's one reason why simulation is so useful

Think of the stock price return distribution-- it doesn't fit into a Gaussian Distribution, but what distribution we can use?

If you read around a little you can find a variety of reasonably good models; none will be perfect.

A relevant, but probably narrower question is, is there any research done along the line of sensitivity analysis? By "sensitivity analysis" I mean we assume known distributions for the variables, but we perturb them a little by slightly changing the distribution shape or slightly changing some of the variables, will the outcome of the simulation results remain roughly the same, or completely different?

Yes, in a variety of guises (and not just for simulation; it's a standard tool in robustness for example) -- but the perturbations needn't be small; you can investigate the effect of just about any form of variation from the base assumptions.
In robustness the effect of small perturbations in distribution is considered through tools like influence functions, empirical influence functions and sensitivity curves (and also via simulation)
The first several books at the above wikipedia page are a good starting place for references on robustness; I don't recall exactly what's in which book (I read Hampel et al in the mid 80's and Huber a year or two later, and some of the others since - it's been a while), but the Hampel et al book does discuss influence functions, so I'd start there I guess.
Edit: TooTone reminded me that I wanted to mention resampling methods, which can be thought of as a kind of simulation. For example, with simple bootstrapping, you use the ECDF (the cdf of the sample) rather than the assumed distribution to sample from. In more complex resampling schemes some function of the data (such as model residuals) may be resampled. So these approaches needn't rely on some parametric assumption about the distribution the data were drawn from.
(Then again, there's also the parametric bootstrap which might be as readily thought of as a particular simulation technique as bootstrapping.)


text:
Q: Pygame event: key up event triggering without releasing key I am trying to make a tetris game and below is my code to make the blocks move. I want the block to keep moving when an arrow key is held down and to stop when it is released. But when I run the code, it stops the block even if the key isn't released.
   def set_keyboard_dirs(cur_block, width, height, events): # events stores pygame.event.get() as I use it multiple times in my code
        global move_timer # only moves block one time per set number of frames
        cur_block.reset_collisions(height)
        for event in events:
            if event.type == pygame.KEYDOWN:  # sets magnitude and direction of movement
                if event.key == pygame.K_RIGHT:
                    cur_block.dir = (cur_block.length, 0)
                elif event.key == pygame.K_LEFT:
                    cur_block.dir = (-cur_block.length, 0)
                elif event.key == pygame.K_DOWN:
                    cur_block.dir = (0, cur_block.length)
                elif event.key == pygame.K_UP:
                    cur_block.rotate(height, width)
                elif event.key == pygame.K_SPACE: # just moves the block instantly to the bottom of the screen by equating it to a 'projection' already there.
                    cur_block.shape = deepcopy(cur_block.projection)
            elif event.type == pygame.KEYUP:  # stops block from moving
                print(event.key) # I called this to see what's happening, and event.key is printed event when I didn't release the key.
                cur_block.dir = (0, 0)

        cur_block.move()

Because of the above, the block moves one step at a time instead of continuously (for as long as they are holding it) like I want. How can I fix it please? The rest of the game works so I really want this to work too. Thanks a lot in advance.
EDIT:
I have also tried setting controls using pygame.key.get_pressed() as follows:
def set_keyboard_dirs(cur_block, width, height):
    global move_timer, keys
    cur_block.reset_collisions(height)
    cur_block.dir = (0, 0)
    if keys[pygame.K_UP] or keys[pygame.K_w]:
        cur_block.rotate(height, width)
    elif keys[pygame.K_SPACE]:
        cur_block.shape = deepcopy(cur_block.projection)
    elif (keys[pygame.K_DOWN] or keys[pygame.K_s]) and 2 not in cur_block.collisions: # 1, 2, 3 are collisions in left, down and right directions
        cur_block.dir = (0, cur_block.length)
    elif (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and 1 not in cur_block.collisions:
        cur_block.dir = (cur_block.length, 0)
    elif (keys[pygame.K_LEFT] or keys[pygame.K_a]) and 3 not in cur_block.collisions:
        cur_block.dir = (-cur_block.length, 0)
    else:
        print('ran reset') # this statement print even as i'm holding down a key for some reason
        cur_block.dir = (0, 0)
    if cur_block.dir != (0, 0) and move_timer == 0:
        cur_block.move()
        move_timer = 7

in the former case, if I remove the KEYUP event and in the latter case if I remove the else statement, the block moves continuously (but cannot stop) which also shows that it is those statements are what is causing the problem, I think. And this is the only place is my code where I define my cur_block.dir as well.

A: That is probably because your for loop runs 1 time per frame, so if you hold down your button it count as you pressed it 1 time at that specific frame, same with the KEYUP events.
You can try to make two variables outside of the mainloop left=False and right=False
And outside of your current for loop, you check if any button pressed.
#these are outside of the mainloop
left=False
right=False

keys = pygame.key.get_pressed()  # checks for key events (put this outside of the for loop, but still be inside your mainloop)
if keys[pygame.K_LEFT]:
    right = False
    left = True
elif keys[pygame.K_RIGHT]:
    left = False
    right = True

# if none of those buttons pressed, it sets the values back to False
else:
    right = False
    left = False

# using the left value, if its true, it will do your action every frame,
#(you can adjust the speed of your block later)

if left:
    #  do something
    cur_block.dir = (-cur_block.length, 0)
if right:
    # do something else

and then if you press LEFT key for example, the value of Left will be true, and then you can check: if any of those values true > do something.
Based on your example code, this is the only thing that I can come up with. I hope it works.

A: In your code the movement of the block is canceled if any key is released, not if the special key is released. You would have to implements special cases if  on of the cursor keys is released:
elif event.type == pygame.KEYUP:
    if event.key == pygame.K_RIGHT:
        # [...]
    elif event.key == pygame.K_LEFT:
        # [...]
    # [...]

I recommend to set the movement direction, dependent on the key states which are returned by pygame.key.get_pressed():
def set_keyboard_dirs(cur_block, width, height, events):
    global move_timer
    cur_block.reset_collisions(height)

    keys = pygame.key.get_pressed()

    cur_block = [0, 0]
    if key[pygame.K_RIGHT]:
        cur_block.dir[0] += cur_block.length
    if key[pygame.K_LEFT]:
        cur_block.dir[0] -= cur_block.length
    if key[pygame.K_DOWN]:
        cur_block.dir[1] += cur_block.length
    if key[pygame.K_UP]:
        cur_block.rotate(height, width)
    if key[pygame.K_SPACE]:
        cur_block.shape = deepcopy(cur_block.projection)

    cur_block.move()


text:
Q: How to get the sum of the values in a $N \times N$ table? How to get the sum of the values in a $N \times N$ table (without adding repeating products such as $6 \times 7$ and $7 \times 6$ twice and without counting perfect squares)?
Figured out that
$1 \cdot 0+2 \cdot 1+3 \cdot (1+2)+4 \cdot (1+2+3)+\dots+n\cdot (1+2+3+\dots+(n-1))=1\dbinom{1}{2}+2\dbinom{2}{2}+3\dbinom{3}{2}+4\dbinom{4}{2}+\dots+n\dbinom{n}{2}$
At this point I'm completely stuck. What do I do to get an exact number e. g. for $n=50$, $n=100$ etc.?

A: If I understand correctly, you want
$$\begin{align*}
\sum_{i=1}^{N-1}\sum_{k=i+1}^Nik&=\sum_{k=2}^N\sum_{i=1}^{k-1}ik\\
&=\sum_{k=2}^Nk\sum_{i=1}^{k-1}i\\
&=\sum_{k=2}^Nk\left(\frac{k(k-1)}2\right)\\
&=\frac12\sum_{k=2}^N\left(k^3-k^2\right)\\
&=\frac12\sum_{k=2}^Nk^3-\frac12\sum_{k=2}^Nk^2\\
&=\frac12\left(\frac14N^2(N+1)^2-1\right)-\frac12\left(\frac16N(N+1)(2N+1)-1\right)\\
&=\frac18N^2(N+1)^2-\frac1{12}N(N+1)(2N+1)\\
&=\frac{N(N+1)}{24}\Big(3N(N+1)-2(2N+1)\Big)\\
&=\frac1{24}N(N-1)(N+1)(3N+2)\;,
\end{align*}$$
if I made no careless algebraic errors. This is the sum of all products of unordered pairs of integers from the set $\{1,\dots,N\}$.

A: Its almost either upper diagonal or lower diagonal matrix entries.
Lets check this in C programming.
:
A[N][N] be the NxN table(A[2][3] gives the value of the cel (2,3) in NxN table)
$for(i=1;i<N;i++)$
{
 $for(j=i+1;j<=N;j++)$
 {
  Sum=Sum+A[i][j];
  }
 }
get the value of Sum.
actual code
#include stdio.h
#include conio.h
void main()
{
 int n,i,j;
 float A[100][100],Sum=0.0;
 clrscr();
 printf("Enter the order of matrix\n");
 scanf("%d",&n);
 printf("Enter the value of the matrix one by one\n");
 for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
   scanf("%f",&A[i][j]);
   }
  }
 printf("Entered matrix\n");
 for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
   printf("%f\t",A[i][j]);
   }
   printf("\n");
  }
 $for(i=1;i<n;i++)$
 {
 $ for(j=i+1;j<=n;j++)$
  {
   Sum=Sum+A[i][j];
   }
  }
 printf("Sum=%f\n",Sum);
 getch();
 }


text:
Q: Json keeping added keys together without creating new dicts I am trying to figure out how to keep keys that are added together. I have written this little script which adds key and value every time its run but it keeps adding dicts.
import json
import datetime

key = str(datetime.datetime.now())
insert = 'Test'
logged = {key : insert}

data = json.load(open('StartLog.json', 'r'))
with open('StartLog.json', 'w') as f:
    data['Logs'].append(logged)
    json.dump(data, f, indent=2)

The output currently would be:
{
  "Logs": [
    {
      "2018-08-28 22:07:12.540188": "Test"
    },
    {
      "2018-08-28 22:07:20.134817": "Test"
    }
  ]
}

I would like the output to be:
{
  "Logs": [
    {
      "2018-08-28 22:07:12.540188": "Test",
      "2018-08-28 22:07:20.134817": "Test"
    }
  ]
}

A: Change Logs within data to a dictionary and update the dict with each entry:
import json
import datetime

key = str(datetime.datetime.now())
insert = 'Test'
logged = {key : insert}

data = json.load(open('StartLog.json', 'r'))
with open('StartLog.json', 'w') as f:
    data['Logs'].update(logged)
    json.dump(data, f, indent=2)

So StartLog.json should start as:
{
  "Logs": {
  }
}


text:
Q: Django: How to delete child row and remove relationship from Foreign key What I want
I have two Models. I want the following outcomes:

*

*When the RecordModel is deleted - The BookingModel remains the same but removes relationship to RecordModel.

*When the BookingModel is deleted - RecordModel is not deleted.

What I've tried
When trying to delete RecordModel. I receive error:
MySQLdb._exceptions.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`cdt_dashboard`.`emissions_dashboard_bookingmodel`, CONSTRAINT `emissions_dashboard__record_id_f8312a32_fk_emissions` FOREIGN KEY (`record_id`) REFERENCES `emissions_dashboard_recordmodel` (`i)')

Models
class RecordModel(models.Model):

    created = models.DateTimeField(blank=True, null=True)
    started = models.DateTimeField(blank=True, null=True)
    finished = models.DateTimeField(blank=True, null=True)

class BookingModel(models.Model):
    booker = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.DO_NOTHING)

A: Try changing
record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.DO_NOTHING)

into this
record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.SET_NULL)


text:
Q: Convert BLOB image to PNG, JPG with Python I have several blob images in Oracle, so I read them with python.
I can correctly read and convert images from a certain table1 with my code, but when changing to  table2 I cannot execute the same code because I get the following error.
cannot identify image file <_io.BytesIO object at 0x000000000C4520A0>
This is my code:
import pandas as pd
import cx_Oracle
from PIL import Image
#[connection to database with connecting string `conn`]
#[query to acces 1 single image]
result = pd.read_sql(query, conn) #connection to db
img = result["IMAGE"][0].read()  # reading the first BLOB result
pre_img = io.BytesIO(img)
Image.open(pre_img)

This code works well, so the only problem is when I try to read images from table1 . Also at SQL developer I can previsualize the photos from table1, but not with table2. The type of data is BLOB as describe(table) says in Oracle.
value of img can be found here

A: This code worked for me
import base64
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodebytes(img))

A: Install Pillow module
py -m pip install Pillow

Use the module to show or save the file from the blob
from PIL import Image

file = request.files['file']
img = Image.open(file.stream)
img.show()
img.save("imagefile.jpg")


text:
Q: Laravel file upload storage link working but public link is not This is in Nova but I think the issue is with how I've setup the filesystem. But just for the full context: I use the Nova Image field to upload an image.
In my config/filesystems:
'blog' => [
  'driver' => 'local',
  'root' => storage_path('app/public/blog'),
  'url' => env('APP_URL').'/storage/blog',
  'visibility' => 'public',
],

The file is uploaded correctly and a preview shows in Nova, both locally and on production. The preview uses the URL example.com/storage/blog/filename.jpg.
On the front-end I use asset('blog/'.$post->image) to display the image. The URL generated is example.com/blog/filename.jpg.
The weird thing is that this last URL works locally, but not on a production server (gives a 404). Does this have to do with folder/file permissions?
I have ran php artisan storage:link and on the server I can actually see the file both in app/public/blog and in public/storage/blog.


text:
Q: Surface plot with different number of points in x, y and z axis I'm trying to plot a surface plot with 549 points.
The x axis has 51 points and y-axis has 9 points.
and the z-axis has 549 points. For example:
fig  = plt.figure()
X = list(xrange(0,51))
Y = list(xrange(0,9))
Z = list(xrange(0,459))

print len(X)
print len(Y)
print len(Z)
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X,Y,Z, cmap=plt.cm.jet, cstride=1, rstride=1)
plt.savefig('graph-1' + '.jpg', bbox_inches='tight', pad_inches=0.2,dpi=100)
plt.clf()

And I try to plot it I get the following error:
ValueError: shape mismatch: two or more arrays have incompatible dimensions on axis 1.

How do we plot when we have different axis lengths?
The 3-tuple looks like this:
for a in range(0,len(X)):
 for b in range(0, len(Y)):
  for c in range(0, len(Z)):
    print (a,b,c)

A: Thanks to @Andrey
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

def fun(x, y):
        return test[x][y]

global test
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = list(xrange(0,9))
y = list(xrange(0,51))
test = [[a for a in range(0, len(y)] for b in range(0, len(x))]
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

A: Edit:
Ok, looking at this again, you want to plot 459 point, on a grid.  Using this loop:
for a in range(0,len(X)):
    for b in range(0, len(Y)):
        for c in range(0, len(Z)):
            print (a,b,c)

will give you many more than 459 points, it will give you 51*9*459 points.
try this:
import itertools
X2,Y2=zip(*list(itertools.product(X,Y)))

This will create all possible combinations of x,y then you should be able to plot (X2,Y2,Z).  len(X2) and len(Y2) are both 459


text:
Q: Значение по умолчанию у родительской модели есть метод:
public function getPaymentText($id)
{

     return self::PYAYMEN;

}

От класса наследуются 4 класса, нужно сделать так чтобы если есть такое значение PYAYMEN у данного класса, то перезаписываем то

A: Есть такая штука называется позднее статическое связываение.
public function getPaymentText($id)
{
    return static::PYAYMEN;
}

Теперь если в классе наследнике объявлена константа PYAYMEN значение будет браться из нее, если нет то с родительского класса, грубо говоря.


text:
Q: find element in list 1 that is in list 2 I have written the following code to find elements in a list that are also within another list. However This algorithm is n squared in Big O, is there a better way of getting around this?
thanks in advance
def printCommon(list1,list2):
    for i in list1:
        found = False
        for j in list2:
            if i == j:
                print i
                break
if __name__ == "__main__":
    list1 = [1,2,3,4,5]
    list2 = [9,8,7,6,5]
    printCommon(list1,list2)

A: As a more efficient way you can use set.intersection :
>>> set(list1).intersection(list2)
set([5])

A bench mark:
from timeit import timeit

s1="""
def printCommon(list1,list2):
    for i in list1:
        found = False
        for j in list2:
            if i == j:
                #print i
                break

list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
printCommon(list1,list2)
"""
s2="""
list1 = [1,2,3,4,5]
list2 = [9,8,7,6,5]
set(list1).intersection(set(list2))
    """

result :
first:  0.129281997681
second :  0.0606861114502


text:
Q: Chart.js drawing only in the top of canvas I am using very slightly modified version of chart.js, my globals look like this
var barChartDemo = new Chart(ctx).Linechart(barChartData, {
  responsive: true,
  scaleShowHorizontalLines: false,
  scaleShowVerticalLines: false,
  tooltipYPadding : 8,
  animateScale : true,
  animationEasing : "easeOutBounce",
  pointDotRadius : 3,
  pointDotStrokeWidth: 3,
  tooltipCornerRadius : 0,
  tooltipFillColor : 'rgba(0,160,0,0.8)',
  scaleLineColor : 'transparent',
  scaleFontSize : 16,
  scaleFontColor : '#8ba2b0',
  scaleFontStyle : 'bold',
  showXAxisLabel:false,
  bezierCurve:false,
  datasetStrokeWidth:3
});

You can see the showXAxisLabel option which I added.
The source of chart.js was modified somewhere in the middle around line 1678 and it looks like this.
if(this.showXAxisLabel){ // just added this check
  ctx.save();
  ctx.translate(xPos, (isRotated) ? this.endPoint + 12 : this.endPoint + 8);
  ctx.rotate(toRadians(this.xLabelRotation) * -1);
  ctx.font = this.font;
  ctx.textAlign = (isRotated) ? "right" : "center";
  ctx.textBaseline = (isRotated) ? "middle" : "top";
  ctx.fillText(label, 0, 0);
  ctx.restore();
} // and this closing bracket

Everything is working fine. Almost always but for some reason the chart is always drawn on top of the canvas and it looks like this.

And to be honest with you all, I also have written an extension for the chart, which is just drawing the background and a line which is not visible in this chart.
Chart.types.Line.extend({
  name: 'Linechart',
  initialize: function(data){
    Chart.types.Line.prototype.initialize.apply(this, arguments);
    this.originalClear = this.clear;
    this.clear = function () {
      var datasets = this.datasets[0];
      var barHeight = 30;
      this.originalClear();
      var x = this.scale.calculateX(0)-5;
      var xmax = this.scale.calculateX(datasets.points.length)-x;

      this.chart.ctx.fillStyle = '#fff';

      var i = 0;
      var odd = false;

      while(i<180){
        if(!odd)
          this.chart.ctx.fillRect(x, i, xmax, barHeight);

        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.strokeStyle = "#cacbcc";
        ctx.moveTo(x-3, i);
        ctx.lineTo(xmax+5, i);
        ctx.stroke();

        odd = !odd;
        i = i+barHeight;
      }

      i = x;
      while(i < ctx.canvas.width){
        ctx.beginPath();
        ctx.lineWidth = 0.5;
        ctx.strokeStyle = "#cacbcc";
        ctx.moveTo(i, 0);
        ctx.lineTo(i, 180);
        ctx.stroke();
        i=i+50;
      }
    }
  },
  draw: function (ease) {
    var points = this.datasets[0].points;
    var y = this.scale.calculateY(goalLine);
    var x = this.scale.calculateX(points.length);
    var xmin = this.scale.calculateX(0)-5;
    Chart.types.Line.prototype.draw.apply(this);
    drawLine(ctx,x,y,xmin);
    drawTextBG(ctx,goalLabel,font,x/3,y-12/2);
  }
});

The two helper functions drawLine and drawTextBG are defined as follows
function drawLine(ctx,x,y,xmin){
  ctx.beginPath();
  ctx.lineWidth = 2;
  ctx.strokeStyle = orange;
  ctx.moveTo(xmin, y);
  ctx.lineTo(x, y);
  ctx.stroke();
}

function drawTextBG(ctx, txt, font, x, y) {
  ctx.save();
  ctx.font = font;
  ctx.textBaseline = 'top';
  ctx.fillStyle = orange;
  var width = ctx.measureText(txt).width;
  ctx.fillRect(x-width-10, y-1, width+20, parseInt(font, 10)+2);
  ctx.fillStyle = '#fff';
  ctx.fillText(txt, x, y+1);
  ctx.restore();
}

Could you please tell me why the chart is drawn like this? And another question would be if it is possible to extend the chart area to fit the line if it's y value is higher than the maximum value of the datasets?
Thanks to everybody who even bothers with this.

A: This problem has no real solution. My problem was, I wanted to show the chart on 100% height of the canvas, which actually worked perfectly. The only thing my added check in the source of the chart.js was to not draw the labels on x-axis. But the calculations for them remained the same and changing the whole source would be painful and time consuming for me. So I left that idea behind and set all the labels as '' (empty) This is still no solution for me, but at least I found out how simple some solutions can be. It is not 100% resolved for me yet, but so that others know, I am looking for other answers.
This is my new question.


text:
Q: Как сделать поля ACF мультиязычными с помощью polylang? Пишут, что polylang совместим с acf, но при добавлении поля acf нигде нет флажков или выбора языка.
У меня много полей, но теперь встал вопрос о мультиязычности. Все записи и страницы можно создать на нужных языках, но при добавлении поля acf нет такой возможности.

A: В functions.php добавьте:
add_filter('pll_get_post_types', 'fixwp_add_acf_pll', 10, 2);
function fixwp_add_acf_pll( $post_types, $is_settings ) {
    $post_types[] = 'acf';
    return $post_types;
}

В настройках Polylang в разделе Synchronization не должно быть галочки на  Custom fields


text:
Q: Ordered set of Dataframe values in Pandas Question:
a series named heights_A with values 176.2, 158.4, 167.6, 156.2, and 161.4. These values represent heights of 5 students of class A.
Label each student as s1, s2, s3, s4, and s5.
another series named weights_A with values 85.1, 90.2, 76.8, 80.4, and 78.9. These values represent weights of 5 students of class A.
Label each student as s1, s2, s3, s4, and s5.
a dataframe named df_A, which holds the height and weight of five students s1, s2, s3, s4 and s5.
Label the columns as Student_height and Student_weight, respectively.
Select the rows corresponding to students s1, s2 and s5 of df_A in the order s2, s5, s1, and capture them in another dataframe df_s2s5s1.
Print the dataframe df_s2s5s1
Wrote to this point on this:
import pandas as pd

import numpy as np

heights_A =  pd.Series([176.2, 158.4, 167.6, 156.2, 161.4])
heights_A.index = ['s1', 's2', 's3', 's4','s5']

weights_A = pd.Series([85.1, 90.2, 76.8, 80.4 , 78.9])
weights_A.index = ['s1', 's2', 's3', 's4','s5']

df_A = pd.DataFrame()
df_A['Student_height'] = heights_A
df_A['Student_weight'] = weights_A
df_s2s5s1 = df_A.loc[(df_A.index.str.endswith('2') | df_A.index.str.endswith('5') | df_A.index.str.endswith('1') ]

print(df_s2s5s1)

But this is not in order of 2,5,1. Could you help on how to get these in order as such.

A: you can use reindex to rearrange the rows.
>>> df_A[df_A.index.str[1:].isin(['1','2','5'])].reindex(['s2','s5','s1'])
    Student_height  Student_weight
s2           158.4            90.2
s5           161.4            78.9
s1           176.2            85.1

Based on data it feels like you want to sort the data on a column after slicing. You can do sorting using sort_values method.
>>> df_A[df_A.index.str[1:].isin(['1','2','5'])].sort_values("Student_height")
    Student_height  Student_weight
s2           158.4            90.2
s5           161.4            78.9
s1           176.2            85.1

A: Another version:
df_s2s5s1 = pd.concat([df_A.loc[df_A.index.str.endswith(str(i))] for i in (2, 5, 1)])

A: Alternate approach:
df_s2s5s1 = df_A.loc[['s2','s5','s1']]
print(df_s2s5s1)

    Student_height  Student_weight
s2           158.4            90.2
s5           161.4            78.9
s1           176.2            85.1


text:
Q: Hyperbolic Geometry Theorem
Prove the perpendicular bisector to AB is perpendicular lo the line IJ and IJ and AB are parallel divergent.
Prove $IJ=\dfrac{1}{2}ED$ prove for angle $A$ acute and obtuse to deduce that in hyperbolic geometry you have $IJ<\dfrac{1}{2} AB$.
So if the angle $A$ is acute or obtuse then I am almost sure there most be a saccheri cuadrilateral $BAED$ but i cant prove the cuadrilateral meets axiom of $BE$ $AD$ congruent to $BE$.
So i have to prove that a segment C perpendicular to segment $AB$ is also perpendicular to other segments parallel to $A$, $ED$ but the triangle doesnt make sense to me any ideas would be great thanks !!!
By angle side angle the bisector divides angle C into equal angles according to bisector definition, so the triangle by $ASA$ into congruent triangles according to me but i cant see a solution-

A: Using SAA criterion, prove that $\triangle BIE\equiv \triangle CIF$ and $\triangle AJD\equiv \triangle CJF$.
From these congruences we get $BE\equiv CF\equiv AD$, hence $BEDA$ is a Saccheri quadriteral with base $ED$.
The line passing through the midpoints of the base and the summit of a Saccheri quadrilateral is perpendicular both to the base and the summit.
Lines which have common perpendicular line are divergent parallel.
Summit of a Saccheri quadrilateral is always greater than the base, hence $AB>ED$.
Finally you have $EI=IF$ and $DJ=JF$ and to prove $IJ=\frac{1}{2}ED$ you have to consider few cases:

*

*Angles $\angle A$ and $\angle B$ are acute.
Then $ED=EI+IF+FJ+JD=2IF+2FJ=2IJ$

*Angle $\angle A$ is right. Then $F=J=D$.

*Angle $\angle A$ is obtuse. Then $ED=EF-FD=2IF-2JF=2IJ$.

*Angle $\angle B$ is right. Case symmetric to 2.

*Angle $\angle B$ is obtuse. Case symmetric to 3.