text:
Q: Who replaced Gandalf as the Grey Wizard? In LotR the Two Towers, it is explained that Saruman has been kicked out of the Wizard council for allying with Sauron.
This allows Gandalf to become the new head of the order and become Gandalf the White. (I feel like this is what happened, but please correct me if I'm wrong).
I was under the assumption that each of the 5 Wizards had their own specific role to fulfil, each with their own purpose and power (hence why Gandalf could break Saruman's staff once he became the White Wizard, as Saruman was previously more powerful than him).
If this is the case, did anyone take up the mantle of the Grey Wizard? Or did a wizard need to die before he could return in another form?
Details from any canon would be appreciated.

A: The Wizards or Istari were 5. The white, the grey, the brown and 2 blue brothers.
I don't think those "roles" and colors would be replaced if someone missing.
Futhermore when the world is about to be split in two between elven/gods people and dying dwarves/taller hobbits/dominating humans. The earth is close to be rounded and the Undying Lands will be cut from human world. Gods won't have more interactions with humans.
I know this isn't exactly the question from OP, but context helps to understand that there is no place for a wizard council anymore.
Imho, Gandalf becoming the white from the grey represents the gift as power the god give him.

A: As far as I know, there has never been any good explanation for why the colors of the wizards were chosen to be what they were. The most prevalent theory involves the Istari taking on the color of the Valar they were associated with, but if you read through the Silmarillion looking for evidence, the theory doesn't really hold up. One thing we do know is that the colors are not a ranking system; though Saruman was appointed the leader of the Istari, the other 4 were all considered equals.
Thus, the only color that seemed to have any significance was the color White -- Saruman's original color, which represented a blending of all other colors. This identified him as the head of the Istari order. Gandalf's Grey color, and Radagast's Brown color, were merely ways to distinguish them from each other. (Even that theory falls apart when you realize there were two Blue wizards.)
Thus, when Gandalf was "promoted" to White, it indicated two things:

*

*Saruman, the previous White Wizard, was no longer considered the head of the Istari order, or even a member of it, and

*Gandalf had taken his place.

No one would need to step in and take over Ganfalf's "position" as Grey Wizard because that color had no more or less importants than the Brown or Blue of the other Istari.

A: I don't think anyone needed to replace Gandalf the Grey. By the time he became Gandalf the White, Sauron's time in middle earth was almost at an end. With no Sauron, the Istari have no mission.

A: I would say (as others have stated before) there's no special meaning to the colours of the wizard.
And I want to raise a point everybody is overlooking (thus, I might be wrong). When the Istari arrived to Middle Earth, there was no leader among them. Indeed, Galadriel wanted Gandalf to be the leader but the Council chose Saruman instead.
Unless they received their clothes after the council, which seems unlikely.
Also, isn't it funny that both Cirdan the Shipwright and Galadriel saw Gandalf was the "good boy" but Saruman was appointed as CEO in the end?
(Please excuse my English, any corrections would be very much appreciated)


text:
Q: Insert into mysql database rather than printing I'm pretty new at  working with Python, and I'm looking to collect Twitter data into my MySQL database for a project. I have my script for collecting data from this tutorial:
import re
from re import sub
import time
import cookielib
from cookielib import CookieJar
import urllib2
from urllib2 import urlopen
import difflib

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0')]

keyWord = 'nyc'
startingLink = 'https://twitter.com/search/realtime?q='

# begin loop

def main():

    oldTwit = []
    newTwit = []
    while 1 < 2:
        try:
            sourceCode = opener.open ('https://twitter.com/search/realtime?q='+keyWord+'&src=hash').read()
            splitSource = re.findall (r'
(.*?)
',sourceCode)
            for item in splitSource:
                #print item
                print ''
                print ''
                print '                           '
                aTweet = re.sub(r'<.*?>', '',item)
                print aTweet
                newTwit.append(aTweet)

            comparison = difflib.SequenceMatcher(None, newTwit, oldTwit)
            howSim = comparison.ratio()
            print '##############'
            print howSim

            oldTwit = [None]
            for eachItem in newTwit:
                oldTwit.append(eachItem)

            newTwit = [None]

            time.sleep(howSim*10)

        except Exception, e:
            print str(e)
            print 'errored in the main try'
            time.sleep(555)

main()

Which provides me with the Tweets I want to collect (I'm not really looking to analyze this data, I'm more experimenting with collecting data automatically using python to connect to my db.)
I also have my database connected using MySQLdb and am able to add content to my database using a simple insert statement:
import MySQLdb
db=MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="twitinfo")
cursor = db.cursor()
sql = "INSERT INTO tweets(text) VALUES ('?')"
cursor.execute(sql)
db.commit()

So my question is how can I 'replace' print with my insert statement, and what do I need to add to make my values the tweet text? I have searched high and low and I'm not finding anything helpful on this. I also tried myself, but as a Python newbie, trying to guess the syntax for this is like finding a needle in a haystack.

A: The SQL you show is inserting a string consisting of a single question mark into the DB.  You need to use VALUES(?) to specify a placeholder for a value, and you need to pass a value to the execute function for it to insert, perhaps like this:
sql = "INSERT INTO tweets(text) VALUES (?)"
value = "Apoplectic Fits"
cursor.execute(sql, value)

You need to add the import line to your Python at the top andconnect to the DB outside the loop.  You can probably put the cursor create line outside the loop.  Inside the loop, you use your tweet message in place of value.

After reading the documentation for MySQLdb (a recommended practice when using a new module), you need to use %s for the placeholder, not ?.
If you want to insert the data in the variable aTweet, then:
sql = "INSERT INTO tweets(text) VALUES (%s)"
cursor.execute(sql, aTweet)

Untested.  In theory, there's no difference between theory and practice; in practice, there is.

redpajama_set_name: RedPajamaStackExchange


text:
Q: use width of images for titles and text I'm trying to create 5 columns where each column has a title, image and some text.  Each may be a different size.  Based on the image width how can I assign that width to the column title and text?
The goal is to have the titles centered above the image and the texts centered below the image and at the same time have all the titles start on the same line, all the images start on the same line and all the texts start on the same line

.column {
  display: flex:
  flex-direction:column;
}

.row {
  display: flex;
  justify-content: space-evenly;
}

.row div{
border:solid 1px red;
text-align:center;}

title1

title2
title2

title3

title4

title5

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam a sagittis lacus, a consectetur mi. Mauris facilisis diam eu dui euismod bibendum. Cras et metus eleifend, sollicitudin nulla ornare, placerat enim. Maecenas in diam in mauris elementum efficitur sed vitae sapien. In hac habitasse platea dictumst. Integer vitae ex non lacus posuere auctor. Quisque nec nibh sed ipsum tempus vulputate et in dui. In dapibus, lacus eget pellentesque lobortis, nunc libero molestie felis, eget sodales nisl magna sit amet metus. Aenean id sapien in ligula iaculis finibus eget id dolor. Aenean non nulla eu ex rhoncus facilisis. Sed efficitur sagittis nulla ultricies venenatis. Vivamus lacinia pulvinar fermentum. Sed mattis tincidunt justo. Morbi finibus cursus lobortis.

Pellentesque hendrerit eleifend lectus. Mauris congue libero quis blandit elementum. Nunc posuere accumsan arcu vitae pellentesque. Pellentesque placerat neque urna, et scelerisque magna sodales sit amet. Nulla consequat mi vel justo vulputate dictum. Phasellus lorem felis, feugiat eget diam mollis, pretium porttitor sem. Etiam viverra sit amet massa sed consectetur. Nam et massa ut massa euismod cursus vel vitae augue. Pellentesque egestas tortor eu odio porttitor tempus.

Quisque sit amet mattis mi. Curabitur vel nunc orci. In vehicula fermentum euismod. Nullam ex justo, sollicitudin nec magna non, malesuada ultricies lacus. Aenean ut scelerisque dolor. Phasellus accumsan volutpat neque ac convallis. Aenean dignissim, felis vitae finibus mattis, ante magna mattis arcu, at ullamcorper nisi sapien eu massa. Nullam vehicula ultricies quam eget finibus. Sed ut fermentum libero, sed accumsan ante. Praesent vel laoreet lacus. Sed interdum, ante sed aliquet auctor, tortor elit viverra turpis, quis posuere nunc erat in purus.

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi sit amet pretium est. Suspendisse dolor orci, lacinia tempus magna ac, tempor rutrum ipsum. Pellentesque tempor erat faucibus faucibus aliquet. Nullam nec aliquam nibh. Mauris et enim facilisis, euismod lectus vitae, tempus ligula. Sed mattis faucibus ligula, at molestie neque sagittis a. Pellentesque eu felis porta, volutpat mauris eu, congue ante. Quisque malesuada sit amet magna vel consectetur. Sed venenatis est et turpis posuere, sit amet pretium erat fringilla. Nunc sit amet nulla nec lectus eleifend faucibus. Donec quam orci, laoreet ut ligula eget, tincidunt auctor ante.

Nunc sed blandit nulla. Cras molestie sem a elit blandit sollicitudin. Curabitur in ex gravida, faucibus felis at, vestibulum nunc. Sed ultricies enim et mi gravida varius a et arcu. Cras id libero leo. Nunc egestas libero dolor, tempus sollicitudin felis varius at. Donec sollicitudin lorem nec ipsum aliquet efficitur. Maecenas interdum libero vitae purus euismod, at fringilla odio posuere. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur pellentesque nisl pellentesque, semper quam ac, commodo tortor.

A: The content elements in the different rows are not siblings. They're cousins.
This means that the content elements in one row have no direct association with the content elements in other rows.
Therefore, they can't be aligned in relation to each other.
More details:

*

*Equal height children of flex items

*Make the longest content item set the width for the entire column

Based on the image width how can I assign that width to the column title and text? The goal is to have the titles centered above the image and the texts centered below the image.

You'll need to alter the HTML (to make all content elements siblings), wait until the CSS subgrid feature or display: contents has solid browser support, or use JavaScript.
More details:

*

*Positioning content of grid items in primary container (subgrid feature)

*What is an alternative to css subgrid?

Here's a solution with a "flattened" HTML structure:

.column {
  display: grid;
  grid-column-gap: 1px;
  text-align: center;
}

.title {
  grid-row: 1;
}

.image {
  grid-row: 2;
}

.text {
  grid-row: 3;
}

title1

title2
title2

title3

title4

title5

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam a sagittis lacus, a consectetur mi. Mauris facilisis diam eu dui euismod bibendum. Cras et metus eleifend, sollicitudin nulla ornare, placerat enim. Maecenas in diam in mauris elementum efficitur
    sed vitae sapien. In hac habitasse platea dictumst. Integer vitae ex non lacus posuere auctor. Quisque nec nibh sed ipsum tempus vulputate et in dui. In dapibus, lacus eget pellentesque lobortis, nunc libero molestie felis, eget sodales nisl magna
    sit amet metus. Aenean id sapien in ligula iaculis finibus eget id dolor. Aenean non nulla eu ex rhoncus facilisis. Sed efficitur sagittis nulla ultricies venenatis. Vivamus lacinia pulvinar fermentum. Sed mattis tincidunt justo. Morbi finibus cursus
    lobortis.

Pellentesque hendrerit eleifend lectus. Mauris congue libero quis blandit elementum. Nunc posuere accumsan arcu vitae pellentesque. Pellentesque placerat neque urna, et scelerisque magna sodales sit amet. Nulla consequat mi vel justo vulputate dictum.
    Phasellus lorem felis, feugiat eget diam mollis, pretium porttitor sem. Etiam viverra sit amet massa sed consectetur. Nam et massa ut massa euismod cursus vel vitae augue. Pellentesque egestas tortor eu odio porttitor tempus.

Quisque sit amet mattis mi. Curabitur vel nunc orci. In vehicula fermentum euismod. Nullam ex justo, sollicitudin nec magna non, malesuada ultricies lacus. Aenean ut scelerisque dolor. Phasellus accumsan volutpat neque ac convallis. Aenean dignissim,
    felis vitae finibus mattis, ante magna mattis arcu, at ullamcorper nisi sapien eu massa. Nullam vehicula ultricies quam eget finibus. Sed ut fermentum libero, sed accumsan ante. Praesent vel laoreet lacus. Sed interdum, ante sed aliquet auctor, tortor
    elit viverra turpis, quis posuere nunc erat in purus.

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi sit amet pretium est. Suspendisse dolor orci, lacinia tempus magna ac, tempor rutrum ipsum. Pellentesque tempor erat faucibus faucibus aliquet. Nullam nec
    aliquam nibh. Mauris et enim facilisis, euismod lectus vitae, tempus ligula. Sed mattis faucibus ligula, at molestie neque sagittis a. Pellentesque eu felis porta, volutpat mauris eu, congue ante. Quisque malesuada sit amet magna vel consectetur.
    Sed venenatis est et turpis posuere, sit amet pretium erat fringilla. Nunc sit amet nulla nec lectus eleifend faucibus. Donec quam orci, laoreet ut ligula eget, tincidunt auctor ante.

Nunc sed blandit nulla. Cras molestie sem a elit blandit sollicitudin. Curabitur in ex gravida, faucibus felis at, vestibulum nunc. Sed ultricies enim et mi gravida varius a et arcu. Cras id libero leo. Nunc egestas libero dolor, tempus sollicitudin
    felis varius at. Donec sollicitudin lorem nec ipsum aliquet efficitur. Maecenas interdum libero vitae purus euismod, at fringilla odio posuere. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Orci varius
    natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur pellentesque nisl pellentesque, semper quam ac, commodo tortor.


text:
Q: Executing a saved Microsoft Access query with pyodbc I am trying to write a Python script to execute a saved query in Microsoft Access using pyodbc.  I connect to the database and retreive the cursor.  If I run:
>>> database_cursor = get_cursor("path_to_database.accdb") #This is a function I wrote that returns the cursor
>>> database_cursor.tables()

I can see the saved query is in there and is of type VIEW.  Jamming it into a namedtuple, it looks like this:
table(catalog='.\\path_to_database.ACCDB', schema=None, name='QueryIWantToExecute', type='VIEW', remarks=None)

If I open my saved query in Microsoft Access and copy-paste the SQL from the SQL view for this query and run the .execute() function, it does indeed return the results of my query.
>>> database_cursor.execute("SQL copy-pasted from Access here")
#This works and returns the results I want

Is it possible to access the SQL from my Python script somehow?  Running the .statistics() method on my returned table yields the following error:
>>> database_cursor.statistics('QueryIWantToExecute')
...some output ommitted...
pypyodbc.Error: ('HY000', '[HY000] [Microsoft][ODBC Microsoft Access Driver] Query support unavailable.')

The .columns() function does return some columns from this table, but I don't see how this gets me to running the query from my script.
>>> database_cursor.columns('QueryIWantToExecute')
[('.\\path_to_database.accdb', None, 'QueryIWantToExecute', 'cause', -9, 'VARCHAR', 20, 40, None, None, 1, None, None, -9, None, 40, 1, 'YES', 1),
 ('.\\path_to_database.accdb', None, 'QueryIWantToExecute', 'CountOfThings', 4, 'INTEGER', 10, 4, 0, 10, 1, None, None, 4, None, None, 2, 'YES', 2)]

Consulting the pyodbc cursor documentation here (https://github.com/mkleehammer/pyodbc/wiki/Cursor), I am only seeing ways to execute queries once you already have the SQL.  How can I pull the SQL from Access?


text:
Q: How is CPU temperature related to clock frequency and processor utilization? While reading Dennis's reply, it makes me think about what determine the CPU temperature.
Following is my understanding.
The CPU temperature is solely determined by the CPU usage in a unit time.
The CPU usage in a unit time is equal to CPU usage percentage times CPU frequency.
So as the CPU usage percentage or the CPU frequency decreases, the CPU usage in a unit time decreases, and the CPU temperature decreases.
Following is a quote of part of Dennis's reply, which my above understanding does not agree with:

Higher usage means higher temperature. Lower usage means lower
  temperature.
Underclocking your CPU frequency with cpufreq will only affect the percentage of CPU usage without lowering the temperature.
The percentage is an absolutely meaningless value. With the exact same workload, your percentage might go up or down when under- or
  overclocking your CPU. But it's still the same workload, so any
  potential harm (and I'm not sure there is any) caused by usage will be
  exactly the same.
Likewise, cpulimit limits the CPU usage, thus keeping percentage and temperature low.

Can you tell me which one is correct, Dennis or me? Why?
Thanks!

A:
The CPU temperature is solely determined by the CPU usage in a unit
  time.  [...]  So as the CPU usage percentage or the CPU
  frequency decreases, the CPU usage in a unit time decreases, and the
  CPU temperature decreases.

Power draw (i.e. heat generated) is not solely determined by CPU utilization, although this but also depends on what instructions the CPU is performing.  In a digital, synchronous CMOS circuit (such as your processor), the power consumption can be computed as:
P = C x V^2 x f

Where C is the capacitance of the digital circuit (changes based on what instructions are being executed), V is the voltage of the CPU, and f is the clock frequency.  Some instructions draw more power than others, so we will assume it's fixed here (i.e. running the same programs that do some appreciable work other than idling).  As a side effect of this, CPU temperature will decrease at idle (just NOPs) even at the same clock frequency.
Note, however, that the power consumed by the CPU is still directly related to the frequency and voltage.  Halving the frequency will drop the power consumption to 50%, while halving the voltage will drop power consumption to 25% of it's original value.  This has a huge effect on heat generation, even if we want to perform the same amount of work (recall that power is work per unit time; see below).

Higher usage means higher temperature. Lower usage means lower temperature.

Yes, this is true.  When your computer is idle, it's often doing "nothing" (i.e. NOP instructions, in a low power state, or simply not doing power intensive instructions).  When it's doing something, like rendering graphics, it uses a lot more components in the CPU (like the ALU, FPU, MIU), generating more heat.

Underclocking your CPU frequency with cpufreq will only affect the percentage of CPU usage without lowering the temperature.

No, this is false.  See the equation above.  Underclocking will cause programs to execute in a longer timespan, but the power consumed by the circuit will decrease.  CMOS power consumption is directly related to the number of logic switches per unit time.

This is very intuitive given the definition of power, which is simply work per unit time, or the rate at which we perform work/computations.  If we run the same program through to completion at a given frequency f, and then compare running it at frequency f/2, in the latter case, although we've taken twice as long to execute the program, we've done the same amount of work - and thus, the power consumed by the CPU during this time will be half.
The CPU will therefore operate at a lower temperature, even though it takes longer to perform the same amount of work, as it now has more time to dissipate the heat in the CPU.  Underclocking also allows operating the CPU at a lower voltage (undervolting), further decreasing the power consumption with no effect on work.

A: Depends on your processor but limiting the CPU maximum can definitely decrease the amount of heat generated. First keep in mind heat is dictated by Vcore voltage not frequency. So if you can limit your processor to a lower P state it will also limit the vcore voltage. Keep in mind this is only on newer Intel processors (I assume AMD as something similar) so I think this is where the confusion is comming from.  I did some tests to prove my theory.

*

*First up I let my I7 3930k @ 4.2Ghz run a pass of linpack and took a screen shot of vcore and temperatures:

As you can see after one pass of linpack my CPU package is at 55C
Now I limited to 75% and ran another pass of linpack:

Notice the differences in vcore at 4.2 Ghz vs 2.4 Ghz, 1.280 and .984. In terms of Vcore that is a HUGE difference. Notice how the heat generated reflects this: 55C vs 40C.
So there is some truth to limiting the frequency lowering the heat generated. Although a CPU at 3.8 GHZ wiht 1.28 Vcore and a CPU at 4.2 Ghz with 1.28 Vcore will generate the same amount of heat so this is only relevant for CPU's that undervolt as well as downclock.

A: What dennis said is
Underclocking your CPU frequency with cpufreq will only affect the percentage only.
It means the workload is same but the percentage will show low(practically it is high). As the work load is higher the CPU temperature will be higher.


text:
Q: Android orientation handling? In my AVD, I hit the keyboard keys to switch the orientation of my AVD, and I have a regular main.xml in my res/layout/ folder and another main.xml in my res/layout-land/ folder. The orientation change is handled by my application, but when it is switched back to portrait, the application remains in the landscape view. What am I doing wrong?

A: Since you're handling the orientation change yourself, you could use setContentView(R.layout.main) in the onConfigchange method.
Also have a look at this, seems like there's a bug in the 2.0 AVD.


text:
Q: "Select Python Interpreter" button not showing (Pycharm) In one of my PyCharm projects, it doesn't show the "Select Python interpreter" button on the lower right-hand side. Here is how it's supposed to be:

However, it's not there. I need it to add an interpreter for my Python project. How do I get this button back (or how to add an interpreter in PyCharm)?
PS: I looked this up, but they told me to go to settings and do it there, but I think they removed this feature in PyCharm 2021.1.

A: Root cause
This happens when there is no .idea/<project-name>.iml file in your .idea/ settings folder for PyCharm or IntelliJ IDEA.
In most cases, this file is modified by VCS.
Workaround
Close your project in PyCharm
Create a backup of your .idea/ folder
Remove .idea/ folder
Re-open your project
Your project will be re-initialised. You could then copy some of the settings files from your backup to your new .idea/ folder.
The solution to the problem is taken from the JetBrains issue tracker forum
source link


text:
Q: GoTo in IntelliJ IDEA does not work I'm developing some js projects (react.js) in IntelliJ IDEA, have many modules linked with export/import, all placed in a tree of folders that is open in my project
anyway, none of IntelliJ's GoTo features work...
can you tell me how to configure quick navigation through function declarations between modules and modules?

A: Usually this is a sign that the caches/indexes for the project are corrupt. Go to File > Invalidate Caches / Restart and select "Invalidate and Restart". After Restarting, wait for IDEA to re-index the project, and then give it a try, Note that invalidating caches will delete your local history (in the event you use that).


text:
Q: ctypes передать массив строк в си. Ошибка: "ctypes.ArgumentError: argument 1: : Don't know how to convert parameter 1" Как передать в С - функцию список слов на Python?
Если заполнять список конструкциями вроде  arr_c[1].append(create_string_buffer(str.encode('asdffg'))) (вызов функции lib.func(arr_c[0], len(all_arr), create_string_buffer(str.encode('test_class')), arr_c[1], create_string_buffer(str.encode('test_word')))) функция:
#ifdef __cplusplus
extern "C" double func(char** news, unsigned n2, char* class_, char** classes, char* word)
#else
double func(char** news, unsigned n2, char* class_, char** classes, char* word)
#endif

Получаю ошибку
ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1
argument 1: <class 'TypeError'>: Don't know how to convert parameter 1

Заранее спасибо!

A: strings = ['one', 'two', 'three']

lib = ctypes.CDLL('some_lib.dll')

array = (ctypes.c_char_p * len(strings))()
array[:] = [s.encode() for s in strings]

lib.func(array, len(strings))


text:
Q: Unset trainable attributes for parameters in lasagne / nolearn neural networks I'm implementing a convolutional neural network using lasagne nolearn.
I'd like to fix some parameters that prelearned.
How can I set some layers untrainable?
Actually, though I removed 'trainable' attribute of some layers,
the number shown in the layer information before fitting, namely, such as
Neural Network with *** learnable parameters                                                never change.
Besides, I'm afraid that the greeting function
in 'handers.py'
def _get_greeting(nn):
    shapes = [param.get_value().shape for param in
              nn.get_all_params() if param]

should be
nn.get_all_params(trainable=True) if param]

but I'm not sure how it affect on training.


text:
Q: gidsignin with swift and firebase: Checking if the user is a new or returning user I have written an app that sign's a user in by using the google signin package and firebase. I would like to write some functionality which would be
if the user has signed into the app using google previously
   then take them straight to the main ViewController
otherwise they must be signing in for the first time
   then bring to a view controller to create a profile

I essentially just want a condition which returns true/false if the user has signed into the app previously, and returns the opposite if this is a new user.

My View Controller
This is my signin view controller, which is the first view visible in my app.
Right now It's only set up to print "new user", if the user has never logged into the app, and "old user" if this is a returning user.
@objc(SignInViewController)
class SignInViewController: UIViewController, GIDSignInUIDelegate{

  @IBOutlet var signInButton: GIDSignInButton!

  var handle: AuthStateDidChangeListenerHandle?

  override func viewDidLoad() {
    super.viewDidLoad()
    GIDSignIn.sharedInstance().uiDelegate = self
    handle = Auth.auth().addStateDidChangeListener() { (auth, user) in
        if user != nil {
            MeasurementHelper.sendLoginEvent()
            dump(UserDefaults.standard)

            //This is the part which I need help with/////////////////////
            if this user has logged in previously
                print("old user")
                self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
            }else{
                print("new user")
                self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
            }
            ////////////////////////////////////////////////////////////

        }
    }
  }

  deinit {
    if let handle = handle {
        Auth.auth().removeStateDidChangeListener(handle)
    }
  }

Other solutions which didn't work for me
This solution looks promising but it only explains how to do it with Facebook and not google.
With this answer the nested if statment if UserDefaults.standard.string(forKey: "uid") != nil && Auth.auth().currentUser != nil { always returns false. The first condition is the one that always return's false, but the second condition is the one that always return's true. (This happens with accounts where I login multiple times, and brand new accounts). When I dump(UserDefaults.standard) I receive
- <NSUserDefaults: 0x2825dd140> #0
  - super: NSObject

The solution which includes checking the last login date with the creation date(newUserRref?.creationDate?.timeIntervalSince1970 == newUserRref?.lastSignInDate?.timeIntervalSince1970
) always returned false for me, so it returned that no user was ever a new user. There's some other solutions on that post that I don't fully understand
The documentation doesn't really explain how to check if this is a first sign in, I can only see it saying how to create a new user or sign in an existing user, but I don't know how I would know when to do what.

A: So this worked at first, but then stopped working, but newUserRref?.creationDate?.timeIntervalSince1970 and newUserRref?.lastSignInDate?.timeIntervalSince197 are almost identical but they differ at the about the 3rd decimal place(One will be Optional(1553623223.055) and the other will be Optional(1553623223.057))
I had to modify the solution from the third posted link to include an extention to the double type, which I place directly at the bottom of my SignInViewControllerClass.
extension Double
{
    func truncate(places : Int)-> Double
    {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}

And then the nested if statement I used to check if the user is new or old is
    if newUserRref?.creationDate?.timeIntervalSince1970.truncate(places: 2) == newUserRref?.lastSignInDate?.timeIntervalSince1970.truncate(places: 2){
        print("new user")
        self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
    }else{
        print("old user")
        self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
    }


text:
Q: Format Excel export file with C# I'm trying to format my C# file in order to Export Data to Excel file.
I would like to center each column and data filled inside.
I use : OfficeOpenXml.Style
I don't know why, but some data into columns don't respect the centered directive.
I have this code :
    /// <summary>
    /// Create excel sheet from a template
    /// </summary>
    /// <param name="almostPreparedData"></param>
    protected override void AlmostPreparedData(IData almostPreparedData)
    {
        var ListeDesGroupesNotationsItemVM = ObjectData.GetObjectValue<ListeDesGroupesDeNotationPsVm>(almostPreparedData);

        using (var package = new ExcelPackage(ExecEnv.Implementation.GetStreamForLocalFile(
            $"App_GlobalResources\\ExcelTemplate\\{LocalizationContextMinimal.CurrentUICulture.TwoLetterISOLanguageName}\\{EXCEL_TEMPLATE}"))
        )
        {
            var worksheet = package.Workbook.Worksheets[1];

            // Insert number of needed lines
            if (ListeDesGroupesNotationsItemVM.Resultat.Count > 2)
            {
                worksheet.InsertRow(6, ListeDesGroupesNotationsItemVM.Resultat.Count - 2, 5);
            }
            else if (ListeDesGroupesNotationsItemVM.Resultat.Count < 2)
            {
                // une ligne est présente en plus dans le template pour faire office de modèle
                worksheet.DeleteRow(5, 1);
            }

            var ligne = 4;
            for (int j = 1; j < 14; j++)
            {
                foreach (var resultat in ListeDesGroupesNotationsItemVM.Resultat)
                {

                    worksheet.Cells[ligne, j].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    worksheet.Cells[ligne, 1].Value = resultat.Nom;
                    worksheet.Cells[ligne, 2].Value = resultat.IdCMCIC;
                    worksheet.Cells[ligne, 3].Value = resultat.NomGac;
                    worksheet.Cells[ligne, 4].Value = resultat.Refbilancielle;
                    worksheet.Cells[ligne, 5].Value = resultat.Cotation;
                    worksheet.Cells[ligne, 6].Value = resultat.Secteur;
                    worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo != null ? resultat.CodeAlgo.ExchangeValue.ToString() : string.Empty;
                    worksheet.Cells[ligne, 8].Value = resultat.CodeSegment != null ? resultat.CodeSegment.ExchangeValue.ToString() : string.Empty;
                    worksheet.Cells[ligne, 9].Value = resultat.DateDerniereCotation;
                    worksheet.Cells[ligne, 10].Value = resultat.StatutsEtapeWorkflow?.ToString() ?? string.Empty;
                    worksheet.Cells[ligne, 11].Value = resultat.Statut ? "Actif" : "Inactif";
                    worksheet.Cells[ligne, 12].Value = resultat.PolePresentateur;
                    worksheet.Cells[ligne, 13].Value = resultat.Pays;
                    ligne++;
                }

            }

            var streamData = DataToolkit.SetStream(package.GetAsByteArray(), null, null);
            Document = new Document(streamData)
            {
                Filename = EXCEL_FILENAME
                    .Replace("{titre}", I18N.Translate("ListeDesGroupesNotation"))
                    .Replace("{date}", DateTime.Now.ToShortDateString()),
                OpenWith = DocumentViewer.ExternalDocumentViewer,
                ContentType = ContentTypes.Xlsx
            };
        }
    }

But when I try to generate my Excel file, I can see some solumns with data uncentered inside. I don't know if my code : worksheet.Cells[ligne, j].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; doesn't work or if the issue comes from another thing ?

Thank you


text:
Q: Migrating data from Package Version x to Package Version y with deleted data Ok,
A follow up to my question here: Unable to access Deleted field (from managed package) from Apex but can from Dev Console
So, we have deleted fields and want to use a post install script to move the data from those fields to a new custom object.

*

*In the package org, a class has been written to perform the migration

*The package is not installed in the package org (as it cannot be installed there duh)

*There is no option to set the package version dependency

So when I install it in the target org, the migration class is versioned to the new version of the package and the fields are not present so it never migrates the data
The class deploys because we use dynamic methods to get the fields and try catch in case the fields do not exist (user deleted)
BUT, there is no way that I can see to version the class for an earlier version of the package so the migration never occurs.
Short of going into every org and running a script in dev console, what would be a way to accomplish this.
Reason for the requirement: Updating code from a package from a previous poorly developed model with 10-30 lookup fields. They are being moved to a related object and the data from those fields needs to be migrated to records in that object.
09-24-2014 - UPDATE: High fives to Tech Evangelists - Issue is now being discuss with R&D to see if there is a way to accommodate this "feature hole" (as I am calling it)

A: Why not creating an intermediate version before the field deletion containing both old and new fields accessible. Then run the migration scripts in the install handler.
And finally after all migration is done use the next version to waste the field.


text:
Q: java close scanner & out of bounds exeption i got two different kind of errors in my code.
one is when someone enters a number that's higher than 8 or lower than 0.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22
    at boter_kaas_en_eiren.Board.placeAttempt(Board.java:37)
    at boter_kaas_en_eiren.Game.play(Game.java:28)
    at boter_kaas_en_eiren.MainClass.main(MainClass.java:12)

the other error is when a player wins and i want to close the scanner so nobody can play anymore.
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.findWithinHorizon(Unknown Source)
    at java.util.Scanner.nextLine(Unknown Source)
    at boter_kaas_en_eiren.Game.play(Game.java:23)
    at boter_kaas_en_eiren.MainClass.main(MainClass.java:12)

if somebody could help me i would appriciate it.
game class
package boter_kaas_en_eiren;

import java.util.Scanner;

public class Game {

    private Board board;
    private boolean gameFinished;

    public Game() {
        board = new Board();
        gameFinished = false;
    }

    public void play() {
        Scanner scan = new Scanner(System.in);
        int x = 0;
        String nextSymbol = "x";

        board.ShowBoard();

        while (gameFinished == false) {
            String input = scan.nextLine();
            int position = Integer.parseInt(input);

            boolean highorlow = board.tohighorlow(position);

            boolean succes = board.placeAttempt(position, nextSymbol);

            if (highorlow) {
                if (succes) {
                    if (nextSymbol.equals("x")) {
                        nextSymbol = "o";

                    } else {
                        nextSymbol = "x";
                    }

                }
            }

            board.ShowBoard();

            if (board.checkWinner("x") == true) {
                System.out.println("x wins");
                scan.close();
            }
            if (board.checkWinner("o") == true) {
                System.out.println("x wins");
                scan.close();
            }

        }

    }

}

main class
package boter_kaas_en_eiren;

public class MainClass {

    public static void main(String[] args) {

        Game game = new Game();

        game.play();
    }

}

board class
package boter_kaas_en_eiren;

import java.util.Scanner;

public class Board {

    private String[] board;

    public Board() {
        board = new String[9];

        for (int i = 0; i < board.length; i++) {
            board[i] = " ";
        }

    }

    public void ShowBoard() {

        System.out.println(board[0] + "|" + board[1] + "|" + board[2]);
        System.out.println(board[3] + "|" + board[4] + "|" + board[5]);
        System.out.println(board[6] + "|" + board[7] + "|" + board[8]);
        System.out.println("");

    }

    public boolean tohighorlow(int position) {
        if (position <= 8 && position >= 0) {
            return true;
        } else {
            System.out.println("Invalid!!");
            return false;
        }
    }

    public boolean placeAttempt(int position, String symbol) {
        if (board[position].equals(" ")) {
            board[position] = symbol;
            return true;
        } else {
            System.out.println("invalid!");
            return false;
        }

    }

    public boolean checkWinner(String symbol) {
        if (board[0].equals(symbol) && board[1].equals(symbol) && board[2].equals(symbol)) {
            return true;
        } else if (board[3].equals(symbol) && board[4].equals(symbol) && board[5].equals(symbol)) {
            return true;
        } else if (board[6].equals(symbol) && board[7].equals(symbol) && board[8].equals(symbol)) {
            return true;
        } else if (board[0].equals(symbol) && board[3].equals(symbol) && board[6].equals(symbol)) {
            return true;
        } else if (board[1].equals(symbol) && board[4].equals(symbol) && board[7].equals(symbol)) {
            return true;
        } else if (board[2].equals(symbol) && board[5].equals(symbol) && board[8].equals(symbol)) {
            return true;
        } else if (board[0].equals(symbol) && board[4].equals(symbol) && board[8].equals(symbol)) {
            return true;
        } else if (board[2].equals(symbol) && board[4].equals(symbol) && board[6].equals(symbol)) {
            return true;
        } else {
            return false;
        }
    }

}

A: If you would thoroughly check the source code lines given in the exceptions, you could probably find the issues yourself. But let's go through it together this time:
ArrayIndexOutOfBoundsException
This means you are trying to access an array element that is simply not there.
In your Game class, you have these two lines:
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);

Looking at tohighorlow(), we find this line:
if (position <= 8 && position >= 0) {
    return true;
}

However, this will return true if the number is in the range [0..8]. In other words, the method returns true when your number is neither too high nor too low. Easiest fix is to change the condition like this:
if (position > 8 || position < 0)

Now numbers greater than 8 or lower than 0 will yield true, which seems to be what the method is supposed to do. Alternatively, you could swap the bodies of the if and else.
Regardless of that, you are ignoring the result of this method when you call placeAttempt() in your Game class. That's not good, because looking at placeAttempt() we find this line:
 if (board[position].equals(" ")) { /* ... */

This is where your exception originates. You are accessing the board array without checking the position value. Or rather, you did check the position value but did not respect the result of that check here. Hence, if position is -2 or 12, for example, you will run into trouble as those elements do not exist (are out of bounds).
IllegalStateException: Scanner closed
Let's simplify the play() method of your Game class for a second:
public void play() {
    Scanner scan = new Scanner(System.in);
    /* ... */

    while (gameFinished == false) {
        String input = scan.nextLine();
        /* ... */

        boolean highorlow = board.tohighorlow(position);
        boolean succes = board.placeAttempt(position, nextSymbol);
        /* ... */

        if (board.checkWinner("x") == true) {
            System.out.println("x wins");
            scan.close();
        }
        if (board.checkWinner("o") == true) {
            System.out.println("x wins");
            scan.close();
        }
    }
}

The first thing you do is to create the Scanner. Now, under certain circumstances (the two if at the end), you close the scanner. However, you do that within a loop. After you close the scanner, the loops starts over with its first line:
String input = scan.nextLine();

But you can't get the next line of a closed scanner.
Additional notes
I noticed that you are quite inconsistent in your style. For example, see these three method names: ShowBoard, placeAttempt and tohighorlow. You use different capitalization for each. I strongly suggest to stick to the recommended naming convention, which means camelCase with lower first letter: showBoard, placeAttempt and tooHighOrLow (also notice to vs too).
Hope this helps.

A: Your array board has the size 9. So if someone enters a number not between 0 and 8 you get an Exception.
You pass the input from the user directly to your function:
board.placeAttempt(position, nextSymbol);

There you do:
 if (board[position].equals(" ")) {

So you try to access an invalid position of the array


text:
Q: If $\tau_n,\tau$ are stopping times with $\tau=\inf_n\tau_n$, then $\text E[X\mid\mathcal F_{\tau_n}]\to\text E[X\mid\mathcal F_\tau]$ Let $(\Omega,\mathcal A,\operatorname P)$ be a probability space.

Lemma 1: Let $Y\in\mathcal L^1(\operatorname P)$, $I\subseteq\mathbb R$ be countable and $(\mathcal G_t)_{t\in I}$ be a filtration on $(\Omega,\mathcal A)$. Then $$M_t:=\operatorname E\left[Y\mid\mathcal G_t\right]\;\;\;\text{for }t\in I\cup\{\operatorname{sup}I\}$$ is an $(\mathcal G_t)_{t\in I\cup\{\operatorname{sup}I\}}$-martingale, where $\mathcal G_{\sup I}:=\sigma(\mathcal G_t:t\in I)$. Moreover, $$M_t\xrightarrow{t\to\operatorname{sup}I}M_{\operatorname{sup}I}\;\;\;\text{almost surely}\tag1.$$

Now let $X\in\mathcal L^1(\operatorname P)$, $(\mathcal F_t)_{t\ge0}$ be a filtration on $(\Omega,\mathcal A)$ and $\tau$ be a $\mathcal F$-stopping time. Then $$\tau_n:=\frac{\lceil 2^n\tau\rceil}{2^n}$$ is an $(\mathcal F_{k2^{-n}})_{k\in\mathbb N_0}$-stopping time for all $n\in\mathbb N$, $(\tau_n)_{n\in\mathbb N}$ is nonincreasing and $$\tau_n\xrightarrow{n\to\infty}\tau.\tag2$$ Assuming that $\mathcal F$ is right-continuous, it holds $$\mathcal F_\tau=\bigcap_{n\in\mathbb N}\mathcal F_{\tau_n}\tag3.$$

How can we use Lemma 1 and $(3)$ to conclude that $$\operatorname E\left[X\mid\mathcal F_{\tau_n}\right]\xrightarrow{n\to\infty}\operatorname E\left[X\mid\mathcal F_\tau\right]\tag4$$ almost surely?

I think the conclusion should be easy given I already wrote, but I'm not able to finish. My idea is to take $Y=\operatorname E\left[X\mid\mathcal F_\tau\right]$ and $\mathcal G_n:=\mathcal F_{\tau_n}$ for $n\in\mathbb N$ in Lemma 1. Then $(M_{\tau_n})_{n\in\mathbb N}$ is an $(\mathcal F_{\tau_n})_{n\in\mathbb N}$-martingale and $M_\tau=\operatorname E\left[M_\tau\mid\mathcal F_{\tau_n}\right]$ for all $n\in\mathbb N$.

A: Suggested modification: "My idea is to take $Y=\operatorname E\left[X\mid\mathcal F_\tau\right]$":
Why don't you consider $Y=X$ in lemma 1?
Rest of Proof:
Then, as you point out, Consider, $\mathcal G_n:=\mathcal F_{\tau_n}$ for $n\in\mathbb N$ in Lemma 1. Then $(M_{\tau_n})$ is an $(\mathcal F_{\tau_n})$ martingale and $M_{\tau_n}=\operatorname E\left[X\mid\mathcal F_{\tau_n}\right]$ for all $n\in\mathbb N$.
Now let us calculate $\mathcal G_{\sup I}$, given (3) :
\begin{align*}
\mathcal G_{\sup I}&=\sigma(\mathcal G_t:t\in I)
\end{align*}
Since in our case $I$ is actually $\mathbb{N}$, $\mathcal G_{\sup I}=\sigma(\mathcal G_n:n\in \mathbb N) = \sigma(\mathcal F_{\tau_n}:n\in \mathbb N)$. But from (3) we have that: $\mathcal F_\tau=\bigcap_{n\in\mathbb N}\mathcal F_{\tau_n}$. So $G_{\sup I}=\mathcal F_\tau$
Now from the second part of Lemma 1, we get that:
\begin{align*}
M_t &\xrightarrow{t\to\operatorname{sup}I} &M_{\operatorname{sup}I}\;\;\;&\text{almost surely}\\
\operatorname E\left[Y\mid\mathcal G_t\right] &\xrightarrow{t\to\operatorname{sup}I}&\operatorname E\left[Y\mid\mathcal G_{\sup I}\right]\;& \text{almost surely}\\
\end{align*}
We now substitute in the appropriate values:
\begin{align*}
\operatorname E\left[X\mid\mathcal F_{\tau_n}\right] &\xrightarrow{n\to\operatorname{sup}\mathbb{N}} \operatorname E\left[X\mid \mathcal F_\tau \right]\;& \text{almost surely}\\
\operatorname E\left[X\mid\mathcal F_{\tau_n}\right] &\xrightarrow{n\to\infty} \operatorname E\left[X\mid \mathcal F_\tau \right]\;&\text{almost surely}\\
\end{align*}
which is the desired result

A: The conditional expectation $\Bbb E[X\mid\mathcal F_{\tau_n}]$ converges a.s. and in $L^1$ to some random variable $Z$, by the martingale convergence theorem. Because $(\mathcal F_t)$ is right continuous, you can take $Z$ to be $\mathcal F_\tau$-measurable. Now check that $\Bbb E[Z\cdot 1_A]=\Bbb E\left[\Bbb E[X\mid\mathcal F_\tau]\cdot 1_A\right]$ for each $A\in\mathcal F_\tau$. This will prove that $Z=\Bbb E[X\mid\mathcal F_\tau]$ a.s.


text:
Q: Check if a place is available by date in Postgresql I am a junior developer and I am trying to create an application to reserve a seat in an open-space on Spring boot with postgresql.
I want to be able to check if the place is not already booked during the duration desired by the user. I already did the database but I'm blocking on how to proceed with the verification.
example : i have already an event :
{
    id:'1',
    name :'Pepito',
    start:'2019-01-01 00:01:00',
    end:'2019-03-06 00:01:00',
    desk_id:'16'
}

start and end columns are timestamp without time zone type.
I want to insert a new event without it happening at the same time as other events having the same desk_id.

A: To check if a workplace is free by date, you need to run the following query:
select case when count(*) > 0 then false else true end as available from my_table WHERE desk_id = $YOUR_DESK_ID and not (
  (start < '$YOUR_START_DATE' and end < '$YOUR_START_DATE')
   or
  (start > '$YOUR_END_DATE' and end > '$YOUR_END_DATE')
);

The query result will return true or false. This way you can check before adding a new record.


text:
Q: dyld: Symbol not found on iOS8/xcode7 I am using xcode 7 to develop an app. Its target OS is iOS8. When i run the app on devices running iOS9 everything works fine but on iOS8 devices the app crashes and i get this error:
dyld: Symbol not found: ___NSArray0__
  Referenced from: /private/var/mobile/Containers/Bundle/Application/xxxxx/xxxxx.app/xxxxx
  Expected in: /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
 in /private/var/mobile/Containers/Bundle/Application/xxxxxx/xxxxx/xxxxxxx


text:
Q: Replacing IP addresses and spaces I'm trying to transform ifconfig -a to give specific output but I am not sure whether sed is performing well. There is a possibility that the particular version of sed isn't performing as it should (due to different sed counterpart).
My ifconfig -a output (I only want to see the netmask):
    xennet0: flags=8863<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST> mtu 1500
            capabilities=2800<TCP4CSUM_Tx,UDP4CSUM_Tx>
            enabled=0
            address: 0a:3d:c0:98:c6:73
            inet 172.31.11.166 netmask 0xfffff000 broadcast 172.31.15.255
            inet6 fe80::83d:c0ff:fe98:c673%xennet0 prefixlen 64 scopeid 0x1
    lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 33184
            inet 127.0.0.1 netmask 0xff000000
            inet6 ::1 prefixlen 128
            inet6 fe80::1%lo0 prefixlen 64 scopeid 0x2

Needed output (transformed output):
 0xfffff000
 0xff000000

My failed attempt:
ifconfig -a | egrep "0xf." | sed 's/inet //' | sed 's/netmask //' |
sed 's/ broadcast//' | sed 's/([0-9]{1,3}\.){3}[0-9]{1,3}//g' | sed 's/\s+//'

It gave me output as:
        172.31.11.166 0xfffff000 172.31.15.255
        127.0.0.1 0xff000000

I expected it to give my needed output.
Help will be of great assistance. I am using NetBSD 6.1.5 (Amazon EC2), however, I believe any general fixture should work.

A: With GNU grep, I'd use Perl regex with the -o option (retain only matches):
$ ifconfig -a | grep -Po '(?<=\bnetmask )\w*'
0xfffff000
0xff000000

For BSD grep, where we don't have the -P option, we can use awk or cut to get the second part only, as in
$ ifconfig -a | grep -o '\bnetmask [^ ]*' | cut -d ' ' -f 2
0xfffff000
0xff000000

If you really want to use sed, you could do this:
$ ifconfig -a | sed -n 's/.*\bnetmask \([^ ]*\).*/\1/p'
0xfffff000
0xff000000

This quite similar to Eric's answer. It suppresses output with -n, and for lines containing netmask, it extracts the word following it and prints it with (the p flag).

A: While doing it with sed might be interesting, I'd recommend awk as the right tool for this (and any similar) job:
ifconfig -a | awk '{ for (i = 1; i < NF; i++) {if ($i == "netmask") { print $(i+1); next; } }}'

A: In some respects, you're making it too hard.  And using more commands than strictly required.  Here's a command line that will do what you want with only one sed(1) invocation:
ifconfig -a | sed -ne '/inet /s/^.* netmask \(.*\) broadcast.*$/\1/p'

Explanation:  the "/inet /" tells sed(1) to select only lines containing that string, and then apply the rest of the expression.  The rest of the expression strips out the netmask from between the keywords "netmask " and " broadcast", and prints the result.
The "-n" on the sed(1) command line tells sed(1) not to print the lines as they're examined.  The "-e" says the next argument is an inline sed(1) script.
Per my comment, that misses lo*.
Changing the pattern to:
'/inet /s/^.* netmask \(0x[0-9a-fA-F]*\).*$/\1/p'

creates the desired results. (including all interfaces running inet, including lo*)

A: Use Grep with Extended Regular Expressions
You can use grep's ERE engine and the --only-matching flag to extract just the hex values. To do this, use egrep or grep -E to turn on extended regular expressions. For example:
$ egrep -o '0x[[:xdigit:]]{8}' /tmp/corpus
0xfffff000
0xff000000

Likewise, you can also pipe in output and get the same results with:
$ ifconfig -a | egrep -o '0x[[:xdigit:]]{8}'

This works with both GNU and BSD greps, and doesn't rely on the PCRE library. It should therefore work on most modern systems without the need to tweak anything.


text:
Q: Using sqlalchemy dburi with Oracle using External Password Store? I am trying to get a oracle sqlalchemy dburi working with an external password store (Oracle Wallet)
I have tried using the standard sqlplus syntax for a external password store with no luck..
sqlalchemy.dburi="oracle:///@PROD"

I can connect successfully using sqlplus as follows:
sqlplus /@PROD

I can't find any information on how to use external password stores with sqlalchemy or turbogears?

A: Off the top comment: Make sure you are running version 5.2.1+ of cx_oracle (http://cx-oracle.readthedocs.io/en/latest/releasenotes.html). Prior to that a bug in SessionPools existed.

A: Based off digging through the source code for sqlalchemy, the correct way to do this is to set the username property (not the database property) of the sqlalchemy.engine.url.URL to your TNS alias for your wallet.
With sqlalchemy.engine.url.make_url
import sqlalchemy.engine.url

url = url.make_url('oracle+cx_oracle://')
url.username = '/@PROD'
engine = create_engine(url)

With sqlalchemy.engine.url.URL
import sqlalchemy.engine.url

url = url.URL('oracle+cx_oracle', username='/@PROD')
engine = create_engine(url)

This is because ultimately, for cx_Oracle to use an Oracle Wallet, you must use the user parameter in cx_Oracle.connect.
e.g.
import cx_Oracle

connection = cx_Oracle.connect(user='/@PROD')
# Because the first parameter in connect is user, the following is also valid
# connection = cx_Oracle.connect('/@PROD')


text:
Q: What is the intended behavior of Datastore.save() when handed an Iterable of objects? I am debugging a bizarre situation involving MongoDB and two programs.
The MongoDB installation in question is initially empty and is a toy deployment.
There are two programs.  One uses Morphia.  The other does not.
The non-Morphia-using program inserts a record into a Service collection in a foo-bar database like so:
mongo << EOF
db.getSiblingDB("foo-bar").getCollection("Service").replaceOne( {
  "service_name" : "argle-bargle"
}, {
  "_id" : "argle-bargle",
  "className" : "com.foo.Service",
  "service_name" : "argle-bargle",
}, {
  "upsert" : true
} )
EOF

The write is acknowledged:
MongoDB shell version v3.4.6
connecting to: mongodb://aura-mongodb:27017/
MongoDB server version: 3.4.6
{
    "acknowledged" : true,
    "matchedCount" : 0,
    "modifiedCount" : 0,
    "upsertedId" : "argle-bargle"
}
bye

The Morphia-using program does this:
final MongoClient client = // ...
final Morphia morphia = new Morphia();
morphia.mapPackage("com.foo");
final Datastore dataStore = morphia.createDatastore(client, "foo-bar");
assert dataStore != null;
dataStore.ensureIndexes();

…followed by:
final Collection<com.foo.Service> services = // ...collection of size 2...
this.dataStore.save(services);

There should now be three items in the database.  There are not.
Connecting with mongo and getting ahold of the Service collection in the foo-bar database and issuing find() shows there to be two (the result of the Morphia-using program's operation).
I HOPE that if I had 20,000 records in that collection that a save(collectionOf2Items) would not delete 19,998 of them!
So then: is save destructive when handed an Iterable?  Any other suggestions on how to debug this baffling problem are greatly appreciated.

A: Hard to tell without any code but if the ID's of the items match calling save() will simply update the existing item.
From Morhpia Quick Tour

Updating data in MongoDB is as simple as updating your Java objects and then calling datastore.save() with them again.

Edit:
For debugging it might be worthwhile to try manually setting the ID fields to an ID you know is not already in use.


text:
Q: How to convert a simple client server TCP program into non blocking one Hi I was reading about non-blocking calls using select() from Beej's guide, but I'm still confused as to how to change my simple client-server code to one that is non blocking. Could anyone tell me what changes do I need to make in the server code as well as the client code for that?
Here's the server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg)
{
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[])
{
     int sockfd, newsockfd, portno;
     socklen_t clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
        error("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0)
              error("ERROR on binding");
     listen(sockfd,5);
     clilen = sizeof(cli_addr);
     newsockfd = accept(sockfd,
                 (struct sockaddr *) &cli_addr,
                 &clilen);
     if (newsockfd < 0)
          error("ERROR on accept");
     bzero(buffer,256);
     n = read(newsockfd,buffer,255);
     if (n < 0) error("ERROR reading from socket");
     printf("Here is the message: %s\n",buffer);
     n = write(newsockfd,"I got your message",18);
     if (n < 0) error("ERROR writing to socket");
     close(newsockfd);
     close(sockfd);
     return 0;
}

Here is the client code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    if (argc < 3) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n = write(sockfd,buffer,strlen(buffer));
    if (n < 0)
         error("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0)
         error("ERROR reading from socket");
    printf("%s\n",buffer);
    close(sockfd);
    return 0;
}

A: The way select(2) makes things non-blocking is by waiting for I/O to become possible without blocking (e.g., when new data is available). When using select(), you wouldn't normally have to put the monitored descriptors into non-blocking mode (with e.g. SOCK_NONBLOCK), so in a sense select() is specifically about avoiding having to use non-blocking I/O.
select() is used to wait for events on multiple descriptors at once. An event here is something that would make it possible to read(2) from or  (depending on how you use select()) write(2) to the descriptor without blocking.
As an example, you could use select() to simultaneously wait for new client connections and data from already connected clients in your server (assuming you extend it to handle multiple clients). To do this, you would use select() to monitor both sockfd and any descriptors you get back from accept(2). Without select(), you would have to use some form of non-blocking I/O (or separate threads) instead to avoid getting stuck in e.g. the accept() until a new client connects, which would prevent you from seeing data from other clients in the meantime. That would be both messier to implement and also less efficient than sleeping in a single location.
select() doesn't do any I/O by itself. It only notifies you when I/O becomes possible without blocking. You pass it a set of descriptors, and it tells you whenever I/O becomes possible on any of them. (And also tells you which descriptors it's possible on.)
In addition to waiting for data on sockets, you could use select() to wait for e.g. user input on stdin at the same time. There are many different types of descriptors that can be select()ed on.


text:
Q: JavaScript - Deleting multiple identical values between two arrays I'm currently working on a code where I need to compare two arrays and remove multiple elements with the same name. Here are the arrays;
vacant = [
"FRAMIA420.2 - 0h 36 m",
"FRAMIA510.4 - 0h 36 m",
"FRAMIA320.7 - 0h 36 m",
"FRAMIA520.7 - 0h 36 m",
"FRAMIA450.3 - 1h 36 m",
"FRAMIA350.1 - 2h 21 m",
"FRAMIA210.2 - 2h 21 m",
"FRAMIA340.2 - 2h 36 m"]

booked = [
"FRAMIA440.5 - 13h 0 m",
"FRAMIA540.2 - 3h 45 m",
"FRAMIA340.2 - 5h 45 m",
"FRAMIA250.1 - 3h 45 m",
"FRAMIA420.2 - 3h 45 m",
"FRAMIA540.1 - 13h 0 m",
"FRAMIA520.5 - 3h 45 m",
"FRAMIA240.4 - 3h 45 m",
"FRAMIA510.2 - 7h 0 m",
"FRAMIA510.4 - 2h 45 m",
"FRAMIA520.7 - 2h 45 m",
"FRAMIA450.1 - 1h 45 m",
"FRAMIA450.3 - 2h 0 m"]

So the similar elements between these two arrays are: FRAMIA420.2, FRAMIA510.4, FRAMIA520.7, FRAMIA450.3 and FRAMIA340.2
I've already filtered out the timestamp part of an element, so I would only need to compare the name parts;
var firstPart = [];
vacant.forEach(function (obj1) {
    firstPart.push(obj1.substring(0, obj1.indexOf('-')))
});
booked.forEach(function (obj2) {
    var c = firstPart.indexOf(obj2.substring(0, obj2.indexOf('-')));
});

The final result should look like this, only leaving the elements inside the vacant -array, that had no similarities with the booked -array:
FRAMIA320.7 - 0h 36 m
FRAMIA350.1 - 2h 21 m
FRAMIA210.2 - 2h 21 m

Note that the similarities between the arrays varies everyday, sometimes there might be 2 similar elements and other days there might be 8 or more.
Any quick and effective way to do this?

A: You can construct a list of all names in the booked array, then iterate through the vacant array, checking for whether that name is in the list of booked names.

vacant = [
  "FRAMIA420.2 - 0h 36 m",
  "FRAMIA510.4 - 0h 36 m",
  "FRAMIA320.7 - 0h 36 m",
  "FRAMIA520.7 - 0h 36 m",
  "FRAMIA450.3 - 1h 36 m",
  "FRAMIA350.1 - 2h 21 m",
  "FRAMIA210.2 - 2h 21 m",
  "FRAMIA340.2 - 2h 36 m"
]

booked = [
  "FRAMIA440.5 - 13h 0 m",
  "FRAMIA540.2 - 3h 45 m",
  "FRAMIA340.2 - 5h 45 m",
  "FRAMIA250.1 - 3h 45 m",
  "FRAMIA420.2 - 3h 45 m",
  "FRAMIA540.1 - 13h 0 m",
  "FRAMIA520.5 - 3h 45 m",
  "FRAMIA240.4 - 3h 45 m",
  "FRAMIA510.2 - 7h 0 m",
  "FRAMIA510.4 - 2h 45 m",
  "FRAMIA520.7 - 2h 45 m",
  "FRAMIA450.1 - 1h 45 m",
  "FRAMIA450.3 - 2h 0 m"
]

function getName(str) {
  return str.substring(0, str.indexOf('-'));
}

var bookedNames = [];
booked.forEach(function (bookedStr) {
  bookedNames.push(getName(bookedStr))
});

var uniqueVacant = [];
vacant.forEach(function (vacantStr) {
  var vacantName = getName(vacantStr);
  if (!bookedNames.includes(vacantName))
    uniqueVacant.push(vacantStr)
});
console.log(uniqueVacant);

A: You need 2 loops, one for each array, and compare the first part of the string of each array, like so:
vacant = [
"FRAMIA420.2 - 0h 36 m",
"FRAMIA510.4 - 0h 36 m",
"FRAMIA320.7 - 0h 36 m",
"FRAMIA520.7 - 0h 36 m",
"FRAMIA450.3 - 1h 36 m",
"FRAMIA350.1 - 2h 21 m",
"FRAMIA210.2 - 2h 21 m",
"FRAMIA340.2 - 2h 36 m"]

booked = [
"FRAMIA440.5 - 13h 0 m",
"FRAMIA540.2 - 3h 45 m",
"FRAMIA340.2 - 5h 45 m",
"FRAMIA250.1 - 3h 45 m",
"FRAMIA420.2 - 3h 45 m",
"FRAMIA540.1 - 13h 0 m",
"FRAMIA520.5 - 3h 45 m",
"FRAMIA240.4 - 3h 45 m",
"FRAMIA510.2 - 7h 0 m",
"FRAMIA510.4 - 2h 45 m",
"FRAMIA520.7 - 2h 45 m",
"FRAMIA450.1 - 1h 45 m",
"FRAMIA450.3 - 2h 0 m"]

for(i=0;i<vacant.length;i++) {
    item1 = vacant[i].split('-')[0];
    for(j=0;j<booked.length;j++) {
        item2 = booked[j].split('-')[0];
        if(item1===item2) {
                console.log('item number '+i+' in vacant is the same as item number '+j+' in booked');
        }
    }
}

https://jsfiddle.net/48hef0cz/

A: Try this :

var vacant = [
"FRAMIA420.2 - 0h 36 m",
"FRAMIA510.4 - 0h 36 m",
"FRAMIA320.7 - 0h 36 m",
"FRAMIA520.7 - 0h 36 m",
"FRAMIA450.3 - 1h 36 m",
"FRAMIA350.1 - 2h 21 m",
"FRAMIA210.2 - 2h 21 m",
"FRAMIA340.2 - 2h 36 m"];

var booked = [
"FRAMIA440.5 - 13h 0 m",
"FRAMIA540.2 - 3h 45 m",
"FRAMIA340.2 - 5h 45 m",
"FRAMIA250.1 - 3h 45 m",
"FRAMIA420.2 - 3h 45 m",
"FRAMIA540.1 - 13h 0 m",
"FRAMIA520.5 - 3h 45 m",
"FRAMIA240.4 - 3h 45 m",
"FRAMIA510.2 - 7h 0 m",
"FRAMIA510.4 - 2h 45 m",
"FRAMIA520.7 - 2h 45 m",
"FRAMIA450.1 - 1h 45 m",
"FRAMIA450.3 - 2h 0 m"];

vacant = vacant.filter(function (element) {
  var roomName = element.split('-')[0];

  var index = booked.findIndex(function (booking) {
    return roomName === booking.split('-')[0];
  });

  return index == -1;
});

console.log(vacant);

A: You can use a dictionary to keep track of unique values.

vacant = [
"FRAMIA420.2 - 0h 36 m",
"FRAMIA510.4 - 0h 36 m",
"FRAMIA320.7 - 0h 36 m",
"FRAMIA520.7 - 0h 36 m",
"FRAMIA450.3 - 1h 36 m",
"FRAMIA350.1 - 2h 21 m",
"FRAMIA210.2 - 2h 21 m",
"FRAMIA340.2 - 2h 36 m"]

booked = [
"FRAMIA440.5 - 13h 0 m",
"FRAMIA540.2 - 3h 45 m",
"FRAMIA340.2 - 5h 45 m",
"FRAMIA250.1 - 3h 45 m",
"FRAMIA420.2 - 3h 45 m",
"FRAMIA540.1 - 13h 0 m",
"FRAMIA520.5 - 3h 45 m",
"FRAMIA240.4 - 3h 45 m",
"FRAMIA510.2 - 7h 0 m",
"FRAMIA510.4 - 2h 45 m",
"FRAMIA520.7 - 2h 45 m",
"FRAMIA450.1 - 1h 45 m",
"FRAMIA450.3 - 2h 0 m"]

vacantDict = {};

vacant.forEach(function(val) {
  var name = val.split(' - ')[0];
  vacantDict[name] = val;
});

booked.forEach(function(val) {
  var name = val.split(' - ')[0];
  if (vacantDict[name] !== undefined) {
    delete vacantDict[name];
  }
});

newVacantList = [];
for (var name in vacantDict) {
  newVacantList.push(vacantDict[name]);
}

console.log(newVacantList);


text:
Q: DevTools failed to load SourceMap: Could not load content for http://localhost:3000/javascripts/bootstrap.js.map: HTTP error: status code 404, net: I get this error when I try to load a layout page that uses bootstrap 5:
DevTools failed to load SourceMap: Could not load content for http://localhost:3000/javascripts/bootstrap.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

I have included the bootstrap.js file link in my head tags yet I still got this warning. Can anyone give me a hint on what the problem might be?

A: It means that you don't currently have a source map being generated for Bootstrap's JavaScript code. Having one would allow you to see unminified code within your browser's console and locate errors in it more easily.
That said, you can either download Bootstrap 5 (Beta 3)'s or ignore the error message, as it will have no realistic impact on any of your users.

A: follow my step.

*

*Download your version of Bootstrap file which you will save in the local directory.
example : i use v.5 bootstrap https://getbootstrap.com/docs/5.0/getting-started/download/
note : bootstrap not include documentation Javascript dependencies like popper, so you must download in another link

*this link popper documentation :
https://www.jsdelivr.com/package/npm/@popperjs/core | v.2.11.6
note : find the folder by include the popper.min.js file. in my case, I found in it the umd folder.

*Lastly, you can deploy with local imports. example, I use Vue :

export default {
    name: 'home',
    head () {
        return {
        title: 'APR',
        link: [
            { rel: 'stylesheet', href: '/bootstrap/css/bootstrap.min.css' }
        ],
        script: [
            { src: "/bootstrap/js/bootstrap.min.js", type: "text/javascript"},
            { src: "/bootstrap/umd/popper.min.js", type: "text/javascript"},
        ]

        }
  }
}

reference sources : https://techglimpse.com/devtools-failed-load-source-map-http-error/


text:
Q: Merging an array of object in React I have an array of object like
[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …],[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …],[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …]

and would like it to merge into one unique array like this
[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …]

I need a unique array in order to render it in a Flatlist.

A: Use Flat
To make your array 1 level deep use the array method flat
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

Use Set
To make an array unique convert it to a Set
const myArray = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(myArray)];

// unique is ['a', 1, 2, '1']

A: Sorry for the confusion, my bad... I should have explained myself better.
Before I was retrieving just page1 of an API which contained 20 items like in this format
[{"popularity": 25.41, "name": "Wan Peng","id": 2187124},{"popularity": 25.238,"name": "Jason Statham","id": 976},…{"popularity": 24.784,"name": "Henry Cavill","id": 73968}]

With that I was able to render the data in a Flatlist easily.
Now I'm fetching 20 pages by looping my API Fetch and concatenating the result
total_results = total_results + resData.results;

my logs now looks like this
RESDATA TOTAL RESULTS: [object Object][object Object][object Object][object Object]

and I'd like it to merge it all in one like this
RESDATA TOTAL RESULTS: [object Object]

Hopefully I managed to clarify my issue a bit better now.


text:
Q: Matrix of objects? I would like to create a matrix of objects, and I would also like to access its elements in a "matrix(i,j)" fashion. I first thought of Boost but as far as I understand Boost matrices are composed of fundamental data types such as int or double, and not by other, more complex objects.
I have also thought about using STL; I remember having seen an STL definition of a 2D matrix using vector twice.
Cheers,
Jose

A: I'm pretty sure that you can use the boost matrix classes for arbitrary types; it's just that a bunch of the numeric algorithms need the elements in the matrix to have numeric-like semantics.
See http://www.boost.org/doc/libs/1_50_0/libs/numeric/ublas/doc/types_overview.htm and http://www.boost.org/doc/libs/1_50_0/libs/numeric/ublas/doc/matrix.htm
Here's an example:
#include <boost/numeric/ublas/matrix.hpp>
#include <string>
int main (int argc, const char * argv [] ) {
    boost::numeric::ublas::matrix <std::string> strMatrix (5, 4);
    strMatrix ( 3, 4 ) = std::string ( "Hello!" );
    return 0 ;
}


text:
Q: Last N posts per category SQL to ORM I'm starting my first Django blog app [after completing the Django official tutorial and Django Girls tutorial]. I'm having some trouble wrapping my head around Django ORM. I have this SQL query that works, but I feel that it is quite inefficient and I rather learn the correct way before going forward.
Post.objects.raw(('SELECT * FROM (SELECT id, category, body, slug, author, title,
published, row_number() OVER (PARTITION BY category) as rownum FROM post) tmp
WHERE rownum < 5'))

Basically I want to display last 5 rows for each post category. The code above is already working, The problem is that when I loop trough each post in my templates it runs additional queries per each post when Post's get_absolute_url method is being called. I fixed this using Django's {% url %} tag but still 7 additional queries are run and I want to limit this to 2-3 max.
I have a model like this :
class Post(models.Model):
    title = models.CharField(max_length=250)
    category = models.CharField(max_length=30, choices=CATEGORY_CHOICES)
    tags = TaggableManager()
    slug = models.SlugField(max_length=250, unique_for_date='published')
    author = models.CharField(max_length=50)
    body = HTMLField('body')
    published = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES,
                             default='draft')

    class Meta:
        ordering = ('-published',)
        db_table = 'post'

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail', args=[self.category, self.slug])

I tried for hours to get this to work via ORM but couldn't make it work. I ended up doing it in raw SQL, but I didnt know that 20+ additional queries will be run. The main goal is to display last 5 posts per category ordered by published date. I am using PostgreSQL.

A: Your solution was almost complete.
from django.db.models.expressions import RawSQL

qs = Post.objects.filter(pk__in=RawSQL(
    'SELECT id FROM '
    '  (SELECT id, '
    '    row_number() OVER (PARTITION BY category ORDER BY published DESC) as rownum '
    '   FROM post) tmp '
    'WHERE rownum < 5',
    []
)).order_by('category', '-published')

Window functions can be used in Django 2.0 instead of RawSQL. (should be updated after 2.0 release)

A: i think you want the last 3 posts, if so you can slice
def mayview(request):
    last_posts = Post.objects.all().order_by('-created_at')[:3]  # list of last posts
    return render(request, 'path/to/template', {'last_posts': last_posts})

in your template use the for loop to unpack the list:
{%for post in last_posts%}

{{post.title}}

{{post.body}}

{{post.created_by}}

{% endfor %}


text:
Q: Wordpress / WooCommerce - dynamic hyperlink based on current product I'm running WooCommerce in Wordpress here and on some products, I will be embedding a block of text which includes a hyperlink to a contact form. I would like the Subject on the contact form to populate with the name of the product where the hyperlink was clicked
I have established that I can populate a CF7 field by appending a query string to the URL (e.g. www...co.uk/contact-form/?subject=blah,blah), so if there was some method of dynamically altering the hyperlink in the aforementioned block of text when the product page is loaded so as to append the product name after the query string
Maybe to describe this a little clearer...
The block of text on the product page will look like this:
Contact us...

Any ideas folks of how I might approach this or has anyone tried something similar?
Thanks

A: So you want the title  of product name ?
$product = wc_get_product( id );

$product_name = $product->get_title();

<a href='...co.uk/contact-form/?subject=<?php echo $product_name; ?>'>Contact us...

If you want the title of the page you can give this parameter to your href
$pageTitle = get_the_title();


text:
Q: Removing starting and ending tags from a string in Perl I have a string like this :
<script>This String may contain other JS tags in between </script>

My requirement is to remove starting and ending Script tag from the string , If the string has some other tags in between , those should NOT be removed.
How can I do this in Perl ?

A: Try the below perl one liner:
perl -lpe "s/<\/?script>//g" inputfile

A: In perl:
$string =~ s!<script[^>]*>|.*</\s*script>!!g;

A: You could try the below code to remove the opening and the closing script tags.
"<script>This String may contain other JS tags in between </script>".replace(/^<script>|<\/script>$/g, "");
'This String may contain other JS tags in between '

OR
"foo <script>This String may contain other JS tags in between </script> foo".replace(/^((?:(?!<script>).)*)<script>(.*?)<\/script>((?:(?!<script>).)*)$/g, "$1$2$3");
'foo This String may contain other JS tags in between  foo'

Through perl,
$ echo 'foo <script>This String may contain other JS tags in between </script> foo' | perl -pe 's/^((?:(?!<script>).)*)<script>(.*?)<\/script>((?:(?!<script>).)*)$/\1\2\3/g'
foo This String may contain other JS tags in between  foo

A: In perl you can do a test to check if it matches your tags, and then do substitution.
#!/usr/bin/perl

use warnings;
use strict;

my $string = '<script>This String may contain other JS tags in between </script>';

if ( $string =~ /^(<script>).*(<\/script>)$/ ) {
$string =~ s/$1|$2//g;
}
print $string, "\n";

this will print:
This String may contain other JS tags in between


text:
Q: IBM DB2 with .NET Core 2.1 I am having issues connection to IBM DB2 instance with the following nuget package:
https://www.nuget.org/packages/IBM.Data.DB2.Core-lnx/1.2.2.100
Code:
static void Main(string[] args)
{
  using (DB2Connection con = new DB2Connection("Server=xxx:8471;Database=xxx;UID=xxx;PWD=xxx"))
  {
    try
    {
      DB2Command MyDB2Command = new DB2Command("select * from xxx.xxx", con);
      con.Open();
      var reader = MyDB2Command.ExecuteReader();
    }
    catch (Exception ex)
    {
      throw ex;
    }
  }
  Console.WriteLine("DONE");
}

Result:

Loading the DB2APP from Appication Assembly Entry point location
Please ensure environment variable LD_LIBRARY_PATH value is set to
  /opt/app-root/src/bin/Debug/netcoreapp2.1/clidriver/lib  ,
  /opt/app-root/src/bin/Debug/netcoreapp2.1/clidriver/lib/libdb2.so
  LIbrary handle written value is a non zero 15186032

The LD_LIBRARY_PATH is set correctly. A quick printenv shows it is.
Also I start the app with this command:
LD_LIBRARY_PATH="/opt/app-root/src/bin/Debug/netcoreapp2.1/clidriver/lib:/opt/app-root/src/bin/Debug/netcoreapp2.1/clidriver/lib/libdb2.so" dotnet run

I get no errors, the program just hangs forever on the open. I had our database team debug on there end and they see the open connection but can give me no further information. Any ideas?


text:
Q: Trigonometric substitution : $a^2-x^2$ why substitute : $x = a \sin t$ On the wikipedia page of trigonometric substitution it says :
Substitution 1. If the integrand contains $a^2 − x^2$, let : $x = a \sin t$.
And my question is : Why not substitute : $x = a\cos t$ ?

A: You can use $x=a\cos{t}$ instead of $x=a\sin{t}$ for $a^2-x^2$, but we usually use $x=a\sin{t}$ because using $x=a\cos{t}$ introduces a negative sign when differentiating because if $x=a\cos{t}$, then $dx=-a\sin{t}\,dt$. Similar things will happen if you use cotangent for $a^2+x^2$ and cosecant for $x^2-a^2$, since they also have negative derivatives.


text:
Q: Capture the onclick event on DialogFragment Can anybody knows how to capture the onclick event on DialogFragment. I need to reset the time if user click on the Dialog (CustomDialog which extends DialogFragment).
Thanks
Mindus


text:
Q: Perl dbd-sqlite, is there a equivalent to the .import function? In many of my scripts I am using sqlite for reporting info and I need first to upload my big table data (millions of csv rows). In the past I have found that .import was quicker than line by line inserting (even using transactions).
Nowadays my scripts implement a method that do system call for sqlite3 db '.import ....'. I wonder if it is possible to call .import from dbd-sqlite. Or it would be better to keep calling insert from system?.
PD: The reason for wanting to call .import from inside dbd-sql is to remove the sqlite3 dependency when my software is installed elsewhere.

A: .import is a SQLite-specific command, so you won't find a DBI method for it which is independent of the database driver; while any given database engine almost certainly has equivalent functionality, each will implement it differently (e.g. SQLite .import vs MySQL LOAD DATA INFILE, &c.)
If you're looking for true engine independence, you'll need to import your data by means of INSERT queries, which can be relied upon in the simplest case to work more or less equivalently everywhere. However, if the difference in execution time is significant enough, it may be worth your while to write an engine-agnostic interface to the import functionality, with a wrapper around each engine's specific import command, and determining from the currently active database driver (or some other method, depending on your code) which wrapper to invoke at runtime.

A: if you are not opposed to "shelling out"
perl -e 'system(qq(sqlite3 foo.db ".import file.dat table")) and die $!'


text:
Q: What is the difference between "summation" and "sum"? Are these sentences grammatically right? which one is more formal? It seems to me that the first group is more convenient, am I right?
Can I say these sentences in other way or in a better format?
a)

The total potential energy of the cylinder is the "summation" of the strain energy and the work done by the external forces.
A is the "summation" of B and C.

b)

The total potential energy of the cylinder is the "sum" of the strain energy and the work done by the external forces.
A is the "sum" of B and C.

Thanks

A: Both would be understood, but b) would be more correct.  The summation is the act of adding the values; the sum is the result of it.


text:
Q: web view in fragment goes to home page every time to press back i have a problem with my web view in fragment that every time press back lead to home page can you help me to make back button goes to previous page .
my fragment jave file includes:-
package com.example.catalogmavbar.ui.cat;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.fragment.app.Fragment;

import com.example.catalogmavbar.R;

public class CatFragment extends Fragment {

    public CatViewModel catViewModel;
    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cat, container, false);
        WebView webView = (WebView)view.findViewById(R.id.webviewncat);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://www.catalogmasr.com/categories");
        return view ;

    }

}

A: You can make a function in fragment to control webview.goBack() that called by onBackPressed() in activity.
Example
in Fragment
CatFragment {
    ...
    public boolean onBackPressedHandled(){
        if (webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return false;
    }
}

in Activity:
Activity {
    ...
    public void onBackPressed() {
        if (!catFragment.onBackpressedHandled()) {
            super.onBackPressed();
        }
    }
}


text:
Q: boolean algebra and simplify boolean expression question1:
from =$ab+ac+a'b'c$ , can I change it to $ab+b'c$ ?
=$ab+ac+a'b'c$
=$c.!(a+a'b')+ab$ -> applied demorgan, am I right?
=$c(a'.(a+b))+ab$
$c(a'a+a'b)+ab$
$a'bc+ab$
$b(a'c+a)$ ->should I apply demorgan again? , but after I apply it, I didn't get
$ab+b'c$

is this true??

question 2:

Boolean algebra :
=$AB+A'B+AB'$
=A(B+B')+B(A+A') -> why $A'B$ changed to B(A+A') , what law is this?

A: Hints:
Question $1$: Note we can write $ac +a'b'c =c(a+a'b')$. Now use absorption law.
Question $2$: Note that $AB+A'B+AB'=AB+AB+A'B+AB'=A(B+B')+B(A+A')$.


text:
Q: VBS Script for Windows Update How would I remove the users request to "approve" everything in this .VBS script and instead just let it autorun/install everything found?
Details on how the script runs:
This .VBS script here runs on the Windows computer, searchs for Windows Update, then manually ask the user to "okay" each update it finds. Once the user hits "okay" and accepts the updates found, it then downloads it.
Once the Widnows Updates downloads, it then asks the user again to approve each Windows Update install. Which is not automated..... I'm not familiar with .VBS enough to edit this script.
Set updateSession = CreateObject("Microsoft.Update.Session")
updateSession.ClientApplicationID = "MSDN Sample Script"

Set updateSearcher = updateSession.CreateUpdateSearcher()

WScript.Echo "Searching for updates..." & vbCRLF

Set searchResult = _
updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")

WScript.Echo "List of applicable items on the machine:"

For I = 0 To searchResult.Updates.Count-1
    Set update = searchResult.Updates.Item(I)
    WScript.Echo I + 1 & "> " & update.Title
Next

If searchResult.Updates.Count = 0 Then
    WScript.Echo "There are no applicable updates."
    WScript.Quit
End If

WScript.Echo vbCRLF & "Creating collection of updates to download:"

Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")

For I = 0 to searchResult.Updates.Count-1
    Set update = searchResult.Updates.Item(I)
    addThisUpdate = false
    If update.InstallationBehavior.CanRequestUserInput = true Then
        WScript.Echo I + 1 & "> skipping: " & update.Title & _
        " because it requires user input"
    Else
        If update.EulaAccepted = false Then
            WScript.Echo I + 1 & "> note: " & update.Title & _
            " has a license agreement that must be accepted:"
            WScript.Echo update.EulaText
            WScript.Echo "Do you accept this license agreement? (Y/N)"
            strInput = WScript.StdIn.Readline
            WScript.Echo
            If (strInput = "Y" or strInput = "y") Then
                update.AcceptEula()
                addThisUpdate = true
            Else
                WScript.Echo I + 1 & "> skipping: " & update.Title & _
                " because the license agreement was declined"
            End If
        Else
            addThisUpdate = true
        End If
    End If
    If addThisUpdate = true Then
        WScript.Echo I + 1 & "> adding: " & update.Title
        updatesToDownload.Add(update)
    End If
Next

If updatesToDownload.Count = 0 Then
    WScript.Echo "All applicable updates were skipped."
    WScript.Quit
End If

WScript.Echo vbCRLF & "Downloading updates..."

Set downloader = updateSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()

Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")

rebootMayBeRequired = false

WScript.Echo vbCRLF & "Successfully downloaded updates:"

For I = 0 To searchResult.Updates.Count-1
    set update = searchResult.Updates.Item(I)
    If update.IsDownloaded = true Then
        WScript.Echo I + 1 & "> " & update.Title
        updatesToInstall.Add(update)
        If update.InstallationBehavior.RebootBehavior > 0 Then
            rebootMayBeRequired = true
        End If
    End If
Next

If updatesToInstall.Count = 0 Then
    WScript.Echo "No updates were successfully downloaded."
    WScript.Quit
End If

If rebootMayBeRequired = true Then
    WScript.Echo vbCRLF & "These updates may require a reboot."
End If

WScript.Echo  vbCRLF & "Would you like to install updates now? (Y/N)"
strInput = WScript.StdIn.Readline
WScript.Echo

If (strInput = "Y" or strInput = "y") Then
    WScript.Echo "Installing updates..."
    Set installer = updateSession.CreateUpdateInstaller()
    installer.Updates = updatesToInstall
    Set installationResult = installer.Install()

    'Output results of install
    WScript.Echo "Installation Result: " & _
    installationResult.ResultCode
    WScript.Echo "Reboot Required: " & _
    installationResult.RebootRequired & vbCRLF
    WScript.Echo "Listing of updates installed " & _
    "and individual installation results:"

    For I = 0 to updatesToInstall.Count - 1
        WScript.Echo I + 1 & "> " & _
        updatesToInstall.Item(i).Title & _
        ": " & installationResult.GetUpdateResult(i).ResultCode
    Next
End If

A: *

*Script output via WScript.Echo method: run your script using the command-line-based script host (e.g. Cscript.exe YourScript.vbs).

*User input: replace strInput = WScript.StdIn.Readline with strInput = "Y" (all occurrences in your script).

*To keep update log: use Cscript.exe YourScript.vbs > YourLog.txt.

Explanation:

*

*Whether you use WScript or CScript, you still run the scripts in the same manner. The difference is only in the output — WScript generates windowed output, while CScript sends its output to the command window in which it was started. On initial installation, the default host is WScript. To change it to CScript, type the following at the command line: cscript //h:cscript.

*I'd not use Cscript.exe YourScript.vbs < Prepared-Y.txt redirection: we don't know number of Y lines in input file as we can't estimate number of updates in advance; could lead to an error Microsoft VBScript runtime error: Input past end of file

*Read Redirection


text:
Q: Reducing code duplication when parsing I prefer to have as little duplicate code as possible within my code base and as such I am constantly looking for ways to reduce it.
I have however become a little stuck on the following case:
Say I have a method that parses output from one program into an object to make it readable in another program.
My current approach is to use regex to scan the input to form a new object for output.
This creates a long list of if statements that look more or less the same with slight variations here and there. Is there a meaningful way to reduce the code duplication here or is this something I have to live with?
if ((match = block.match(/bssid=([A-Fa-f0-9:]{17})/))) {
    parsed.bssid = match[1].toLowerCase();
}

if ((match = block.match(/freq=([0-9]+)/))) {
    parsed.frequency = parseInt(match[1], 10);
}

if ((match = block.match(/mode=([^\s]+)/))) {
    parsed.mode = match[1];
}

if ((match = block.match(/key_mgmt=([^\s]+)/))) {
    parsed.key_mgmt = match[1].toLowerCase();
}

A: I'm guessing you want something like this:
var parseConfig = {
    bssid: {
        expr: /bssid=([A-Fa-f0-9:]{17})/,
        handle: match => match[1].toLowerCase()
    },
    frequency: {
        expr: /freq=([0-9]+)/,
        handle: match => parseInt(match[1], 10)
    },
    mode: {
        expr: /mode=([^\s]+)/,
        handle: match => match[1]
    },
    key_mgmt: {
        expr: /key_mgmt=([^\s]+)/,
        handle: match => match[1].toLowerCase()
    }
};

function parse(block, cfg) {
    var parsed = {};

    Object.keys(cfg).forEach(key => {
        var item = cfg[key],
            match = block.match(item.expr);

        parsed[key] = match ? item.handle(match) : null;
    });

    return parsed;
}


text:
Q: should I use single or plural form here?
...help the children draw the animal(s) they choose.

When each child can only choose one animal, which form is correct?
I guess plural form is correct here, since the "children" is in plural form.

A: If you're talking about only one animal to draw for all the children, then it can be kept singular. Here you are asking them to choose from, so are various animals to draw from, then plural.


text:
Q: How do I add a condition to my find function? so i have this code, what it does is it finds the word "Hello" on a column and if that String is found on the "J" column the entire row would get deleted, but i wanted to retain all the rows with the word "World" in it even though the cell has both "Hello" and "World" in it. For example:
Column J
1 Hello world
2 Hello person
3 Hello everyone
4 Hello person
5 Hello world
6 Hello everyone
7 Hello person
8 Hello world
The only rows that should remain are 1,5, and 8. Thank you, any help would be appreciated.
Sub Test()
Dim c As Range
Dim SrchRng

Set SrchRng = ActiveSheet.Range("J1", ActiveSheet.Range("J65536").End(xlUp))
Do
    Set c = SrchRng.Find("Hello", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing

End Sub

A: I typically recommend using a For loop, starting at the end and working upwards, when you're deleting rows.
This should work for you:
Sub test2()
Dim c As Range, SrchRng As Range
Dim ws as Worksheet
Set ws = ActiveSheet
Set SrchRng = ws.Range("J1", ws.Range("J65536").End(xlUp))

Dim i As Long, lastRow As Long
lastRow = SrchRng.Rows(SrchRng.Rows.Count).Row

With ws
    For i = lastRow To 1 Step -1
        If InStr(1, .Cells(i, 10), "Hello") >= 1 And InStr(1, .Cells(i, 10), "world") = 0 Then
            .Rows(i).EntireRow.Delete
        End If
    Next i
End With
End Sub


text:
Q: Make a matplotlib animation, by clf()'ing each frame i am trying to make the simplest matplotlib animation, using animation.FuncAnimation. I dont care about efficiency. i do not want to keep track of the plotted lines and update their data (in my desired application this would be annoying), i simply want to erase the plot before animating every frame. i thought somthing like this should work, but its not..
import matplotlib.animation as animation

fig = Figure()

def updatefig(i):
    clf()
    p = plot(rand(100))
    draw()

anim = animation.FuncAnimation(fig, updatefig, range(10))

A: At least this seems to work:
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

def updatefig(i):
    fig.clear()
    p = plt.plot(np.random.random(100))
    plt.draw()

anim = animation.FuncAnimation(fig, updatefig, 10)
anim.save("/tmp/test.mp4", fps=1)

The issue with the original code is Figure written with a capital F (should be figure).
Otherwise, I would suggest not to use the pylab style "everything in the same namespace" approach with matplotlib. Also, using the object-oriented interface instead of plt.draw, plt.plot, etc. will save a lot of trouble later on.


text:
Q: Unable to load C++ dll in python I have a C++ dll which I'm trying to use it in Python,
>>> from ctypes import *
>>> mydll = cdll.LoadLibrary("C:\\TestDll.dll")

until now there are no errors, system seem to be doing what I wanted, but when I try to access mydll, the Intellisence in the Python IDLE shows the following,

from the above pic, it's clear that the intellisence doesn't show up any available functions of the dll, but when I checked the same TestDll.dll with dumpbin /EXPORTS TestDll.dll it has 45 functions, but none of those functions are available with python.

Please Note: There are several questions on this topic, I tried the following suggestions but no use,

*

*incompatible version of Python installed or the DLL [TestDll.dll & Python both are 32 bit versions]

*I think ctypes is the way to go [Same Issue, cant see any functions, but loads the dll]

Now my question is how do I load all the available functions(as shown by dumpbin)?
Edit 1
Based on eryksun suggestion, I was able to make some progress. The TestDll.dll comes along with a header file TestDll.h(my bad I missed this file earlier), from which I could see the available Exported Functions.
TestDll.h:
_stdcall Function1 (const char* prtFileString, cont char* prtDescrip, struct FileParams* ptrParsms);

struct FileParams
{
  float val1;
  void* pMarker;
};

now I've tried the following,
>>> mydll = CDLL("c:\\TestDll.dll")
>>> Function1 = mydll.Function1
>>> Function1.restype = c_int

until now it's fine, but when I try to define the argTypes, not sure how to do it for structs?
>>> Function1.argtypes = (c_char_c, c_char_c, ???)

any suggestions are much appreciated.

A: Based on your header, here's a dummy C file (for Windows) that can be used to test a ctypes wrapper.  You mentioned C++ but the example was a C interface, which is a good thing because ctypes works with C functions not C++.
x.c
#include <stdio.h>

struct FileParams
{
  float val1;
  void* pMarker;
};

__declspec(dllexport) _stdcall Function1 (const char* prtFileString, const char* prtDescrip, struct FileParams* ptrParsms)
{
    printf("%s\n%s\n%f %p\n",prtFileString,prtDescrip,ptrParsms->val1,ptrParsms->pMarker);
}

Here's the ctypes wrapper.  Note that ctypes does not inspect the DLL and automatically load all the functions.  You have to declare the functions, parameters and return values yourself.  See ctypes:structures and unions for the Structure syntax.
Also note that for a DLL with _stdcall functions use WinDLL instead of CDLL.
x.py
#!python3
import ctypes

class FileParams(ctypes.Structure):
    _fields_ = [('val1',ctypes.c_float),
                ('pMarker',ctypes.c_void_p)]

    x = ctypes.WinDLL('x')
    x.Function1.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(FileParams)]
    x.Function1.restype = ctypes.c_int

    fp = FileParams(1.234,None)
    x.Function1(b'abc',b'def',ctypes.byref(fp))

And the output:
abc
def
1.234000 0000000000000000