text:
Q: Is there a word or phrase that's the opposite of "drinking the kool-aid"? Is there a word or phrase that's the opposite of "drinking the kool-aid"? That phrase means you've been "on the inside" for so long that you can only see the good things.  I'm looking for a phrase that means you've been on the inside for so long that you can only see the bad things.

A: "Drinking the Kool-Aid" does not mean being on the inside so long you see only good things. It means demonstrating unquestioning obedience or loyalty to someone or something--it could mean seeing only the good things, but that's imprecise. The phrase derives from James Jones' followers at Jonestown, who committed suicide by drinking poisonous Kool-Aid at his command. The opposite of this might be skepticism:

any questioning attitude towards unempirical knowledge or
  opinions/beliefs stated as facts, or doubt regarding claims that are
  taken for granted elsewhere. (wikipedia)

Perhaps also, distrust, mistrust, doubt, opposition, disbelief, to reject an idea, to renounce an idea, to disown an idea
If you really want an insider's perspective that suggests an open-eyed view of the bad things one will encounter there, you might say that person is "in the belly of the beast."
Sometimes people refer to "seeing how the sausage is made," meaning that they are in a position to see the horrible things that go on in a particular place (such as a sausage factory that combines meat by-products that people would never eat in any other form).

A: It's not a parallel construction to "drinking the kool-aid," but the opposite process is becoming jaded.

jaded:  feeling or showing a lack of interest and excitement caused by having done or experienced too much of something
http://www.merriam-webster.com/dictionary/jaded


text:
Q: Executing PHP Function When a Form Submit is Clicked I am having trouble understanding handling variables that are passed through pages when a form submit button is clicked. Basically i have a text area where a user writes an sql query. Then clicks submit. Then on the same page (x.php) , i have to display the results in a table. I figured, when the user clicks the button, i call a function that connects to the database, then runs the query, and outputs the result in a table. The code i have below is a mock, and isnt quite working.But above is essentially what i am trying to do.
In my code, I call the page, and check to see if the proper submit button has been clicked, is that how i am suppose to do it?
Also, I am trying to post the metadata in the code below, but how does the table replace what is already on the page?

<title>CNT 4714 - Project Five Database Client</title>

CNT 4714 - Project Five Database Client

<?php

?>
Welcome Back!

<?php echo $_POST["user"];?>

Enter Query

Please enter a valid SQL Query or update statement. You may also just press

"Submit Query" to run a defualt query against the database!
<form action="" id="sql" method="post">

  <textarea rows="10" cols="50" name="query" form="sql">Enter text here...</textarea>

  <input type="submit" name="submit" color="red">
  <input type="submit" name="" color="red" value="Submit Update">
</form>
<?php

if(isset($_POST['submit'])){
    echo "hello";
   query(); //here goes the function call
}
function query()
{
    echo "hello";
    $conn = mysqli_connect("localhost:3306", "root", "*******", "project4");
    $query = $_POST["query"];
    $result = mysqli_query($conn, $query);
    $metadata = mysqli_fetch_fields($result);
    print("
");
    for($i=0; $i<count($metadata);$i++){
        print("
name);
        print("
");
    }
}

?>

A: You are trying to get the values of the global variable $_POST while you are posing it to $_GET. The way to fix this is assigning the method into your form element.
Example:
<form id="sql" action="" method="POST">

There are many ways for checking or the form is submitted, one of this ways (the one I am always using) is checking or the $_SERVER['REQUEST_METHOD'] is equal to "POST". This way you can tell the different between a GET, POST, or PUT request.
Example:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if(isset($_POST['sql']))
    {
        ....
    }
}

A: If you're using $_POST, your form request method should be POST.
<form action="" id="sql" method="post">
Otherwise, it will submit it with a GET request by default.
In that case, you will have to access the variable using $_GET instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bundle optimization for ruby on Docker I'm new to docker and was wondering how does ruby bundler behave when re-building docker images? The first time I build an image it takes forever to bundle install. What will happen when I add another gem into the Gemfile? Is there a way to ensure previous gems are cached somehow in the image and used for this  new bundling?
Dockerfile:
FROM rails:onbuild
RUN apt-get install -y imagemagick

A: It depends on how you ADD your Gemfile.
ADD Gemfile /var/www/yourapp/
ADD Gemfile.lock /var/www/yourapp/
RUN bundle install

In this case bundle install would only run if either the Gemfile or the Gemfile.lock changed. Note that the placement of this instruction in your Dockerfile matters. As soon as a previous build-steps cache is invalidated all subsequent instructions are no longer cached. (e.g. you ADD a config file before the Gemfile, and that changed -> bundle install will run).

What will happen when I add another gem into the Gemfile?

If you just want to add a couple of gems without bundling everything you could also do something like:
ADD Gemfile /var/www/yourapp/
ADD Gemfile.lock /var/www/yourapp/
RUN bundle install
...
ADD Gemfile.tip /var/www/yourapp/
RUN bundle install

Here is a rails example project you can check out (well documented).


text:
Q: Handlebars IF value contains x.* I have an issue with some JSON I'm parsing into a template.  Essentially, I'm constructing a query via a simple web interface, pulling back data in JSON format, and controlling the data/template with Mustache.
However, I'm unable to query values on nested objects in the JSON via the URL...so I think I need to resort to conditional statements using Handlebars.
Is it possible to run a like or indexof style comparison in an handlebars block helper using wildcards?
i.e.
{{#if folderPath == "content/published/.*"}}
 Render content
Else, do nothing

Appreciate any help,
Thanks

A: I know I'm a little late, but I stumbled across this and it should have an answer.
I wrote a helper for this that works.
Handlebars.registerHelper('contains', function(needle, haystack, options) {
   needle = Handlebars.escapeExpression(needle);
   haystack = Handlebars.escapeExpression(haystack);
   return (haystack.indexOf(needle) > -1) ? options.fn(this) : options.inverse(this);
});

The template should look like this (Expressions, Block Helpers)
{{#contains "content/published" folderPath}}
    something
{{/contains}}

This will only return "something" if the "content/published" is found. No need for wildcards.
This can be used as a sort of switch case using "else". This part wasn't clear to me in the documentation. Should be useful to someone.
{{#contains "content/published" folderPath}}
    Something
{{else contains "content/something" folderPath}}
    Something else
{{else}}
    Something else v2
{{/contains}}

For those using express-handlebars, your implementation will look like this(in RegisterHelpers.js):
var register = function(Handlebars) {
    var helpers = {
        if_op: (a, op, b, options) =>{
            switch (op) {
                case '!=': return (a != b) ? options.fn(this) : options.inverse(this);
                case '!==': return (a !== b) ? options.fn(this) : options.inverse(this);
                case '>=': return (a >= b) ? options.fn(this) : options.inverse(this);
                case '<=': return (a <= b) ? options.fn(this) : options.inverse(this);
                case '==': return (a == b) ? options.fn(this) : options.inverse(this);
                case '===': return (a === b) ? options.fn(this) : options.inverse(this);
                case '>': return (a > b) ? options.fn(this) : options.inverse(this);
                case '<': return (a < b) ? options.fn(this) : options.inverse(this);
                default: return options.fn(this);
            }
        },

        contains: (Needle, Haystack, options) => {
            Needle = Handlebars.escapeExpression(Haystack);
            Haystack = Handlebars.escapeExpression(Haystack);
            return (Haystack.indexOf(Needle) > -1) ? options.fn(this) : options.inverse(this);
        }
    }

    if (Handlebars && typeof Handlebars.registerHelper === "function") {
        for (var prop in helpers) {
            Handlebars.registerHelper(prop, helpers[prop]);
        }
    } else {
        return helpers;
    }
}

module.exports.register = register;
module.exports.helpers = register(null);

A: You can indeed do this, but you'll need to create a custom Handlebars helper.
Your template will end up looking something like
{{#like folderPath '==' 'content/published/.*'}}
  something
{{/like}}

Where #like is the name of your custom helper.


text:
Q: Get category ID from order item inside woocommerce hook In functions.php we have:
add_action( 'woocommerce_order_status_processing', 'mysite_processing', 10, 1);

then inside this function we get order items:
function mysite_processing($order_id) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
    }
}

After getting the product id, we want to get the category id that product belongs. We already try with get_the_terms and has_term functions, both didn't work.

A: Solved, added to items for: $product = wc_get_product( $product_id );

A: Try below code
function mysite_processing($order_id) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $term_list = wp_get_post_terms($product_id,'product_cat',array('fields'=>'ids'));
        print_r($term_list);
        $cat_id = (int) $term_list[0];
        echo $cat_id;
        die();
    }
}


text:
Q: Teams Task/Tab SSO Issue on IOS We have a published app in the Teams App Store.
And we're adding a tab to our bot app and we use SSO to authenticate users.
Here's an example of our project pages:
main.project.com - main page where users do their job.
auth.project.com - the page where users authenticate with SSO.

By default we open "main.project.com" and check if user is authenticated. If user is not authenticated we redirect them to "auth.project.com", they authenticate there and we redirect them back to "main.project.com" afterwards.
This works perfectly on all platforms except IOS.
On IOS we have the App is neither whitelisted nor app resource matches current domain error.
We've made an investigation and it seems like SSO library (on IOS) doesn't check current location on the webView, instead it checks the very first location of the tab app.
Our SSO api address is "api://auth.project.com/{...appID is truncated...}" and we get SSO token from the page with this location.
If we open the TAB with "auth.project.com" as a first page of the tab, we can auth user without any issues.
Is this expected, does it work as intended?
Phone:
    iPhone SE
    IOS version 15.1

Microsoft Teams App
    Version: 4.8.1
    Build: 4.8.77.2022083005/0511 (general)
    Calling Version: 2022.13.01.6
    Release Branch: 2022Apr-T2


text:
Q: I am not able to run parcel from vs code File C:\Users\bartp\AppData\Roaming\npm\parcel.ps1 cannot be loaded because running scripts is disabled on this system. For more information,
see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170
The above is what I keep seeing after trying to load index.html from the terminal in vs Code.
I used the code
parcel ./src/index.html
How do I change this?


text:
Q: Can't connect SQL Server 2016 Developer via connection string generated by .edmx file I'm working on a project using SQL Server 2008 Express. I had an instance called SQLEXPRESS and I used to connect to the DB via this connexion string :
<add name="MyConn" connectionString="metadata=res://*/MyDataModel.csdl|res://*/MyDataModel.ssdl|res://*/MyDataModel.msl;provider=System.Data.SqlClient;
provider connection string="data source=PCNAME\SQLEXPRESS;initial catalog=DbName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

This connection string was generated by .edmx file (I'm working on an ASP.NET MVC project, database first, and Entity Framework) and it worked fine.
I recently installed SQL Server 2016 with a Developer Licence. During the install process, I used the default instance, which is MSSQLSERVER. For information, the generated InstanceID is MSSQL13.MSSQLSERVER.
I have a SQL project in my solution to regenerate my tables on my new SQL Server; I could connect easily to the server via the wizard.
I also used SQL Server Management Studio to verify everything was fine on the server, and it works perfectly (tables are generated, connection was OK).
However, my code is unable to connect to the server and systematically failed to the first call with error 26 - can't locate server instance
Here is what I've tried so far:

*

*Change the data source parameter of the connexion string to localhost , ., .\MSSQLSERVER, .\PCNAME, PCNAME.MSSQLSERVER, PCNAME.MSSQL13.MSSQLSERVER, DOMAIN.MSSQLSERVER, DOMAIN\PCNAME => Doesn't work

*Verify SQL Service are running => They are

*Create an .udp file, connect to my server, and copy/paste the generated connection string : Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyDB;Data Source=PCNAME => Doesn't work

*Regenerate my .edmx file (and the connection stirng) => Doesn't work

*Verify this suggestion => It was already correct

Why does all the connection wizards seems to work (SSMS,
.udl file, .edmx generator, my DB project), whereas my code is unable to reach the server? I didn't change any line of code.
EDIT : The crazy thing is I have a log database on the same server, the connexion string is
<add name="NLogConn" connectionString="Data Source=localhost;initial catalog=DBLOG;integrated security=True" providerName="System.Data.SqlClient" />

And it is actually logging the network error !! So is it really a connection string error or an EF error ? I'm using the latest EF version, 6.1.3 on each project referencing EF (The main and the DAL layers)

A: Before going off the deep end on what it could be let's start with a working connection string I just tested on my local machine on Visual Studio 2017 Enterprise with Entity Framework 6.1.3.
<connectionStrings>
    <add name="TesterEntities" connectionString="metadata=res://*/Tester.csdl|res://*/Tester.ssdl|res://*/Tester.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Tester;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>

The marked up connection string is:
="data source=.;initial catalog=Tester;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"

For my test connection I am using my local server for a default instance also of 2016 developer edition(. is abbreviation for this).  I am using integrated security and my database name(initial catalog) I am targeting is Tester.
There are a few things to consider if Entity Framework(EF) is not properly hitting a target.

*

*What version of EF are you using?  Before MS moved to Core, I believe the last .NET full edition of EF was 6.1.3.  Ensure you are on the most current version on Nuget download.

*If you go from Express to a full fledged SQL the connection string's 'provider' often will not be the same I believe.  Or it could be the local default instance before sql is installed is different.  Ensure you don't overwrite an existing connection string with this.  The provider should be: 'provider=System.Data.SqlClient'

*You are referencing a project of EF in ANOTHER project.  Each project that references EF should be having the NuGet package for EF as well as a config file with the connection string.  EG: I have a console project for testing things I write and reference another project called 'EF Testing' and I don't have an app config with a connection string.  It won't work.


text:
Q: Running VBA Script to Automate Large Data Aggregation Sheet where info is copied from
Destination Sheet
Am currently looking for the most efficient way to copy and paste data from one worksheet (which is an output of a report pulled from a third party system), into another sheet which is a steady state "legacy file" if you will. Essentially, the destination file is a repository of different years / months of data with 3 distinct categories along the column headers (for now we can call them x,y,z). These categories each have distinct attributes, in example let's focus on x, this will have 4 attributes attached to it, think

*

*Customer,

*Customer selling point

*Product ID sold to customer

*Product Name

based on the information pulled from the system. I need to find a way to:

*

*Pull the data from one sheet to the other, starting first with the distinct attributes (which are text and numerical mixed), and based on the 3 distinct categories, then paste special value these column headers along the rows for each of the attributes

I am just taking this process over now, it is extremely time consuming and was being done manually previously and I am not willing to spend 2-3 hours doing something that can be automated. I have started on my code below, but am stuck on the pasting special values based on column headers:
 Dim wsCopy As Worksheet
 Dim wsRR As Worksheet
 Dim wsRRPiv As Worksheet
 Dim lcopylastrow As Long
 Dim lRRLastRow As Long

'Setting variables for report support workbook as well as download
'

    Set wsCopy = ActiveWorkbook.Worksheets(1)
    Set wsRR = ThisWorkbook.Worksheets("Data")
    Set wsRRPiv = ThisWorkbook.Worksheets("Pivot")

'This will activate the workbook and work sheet which as the data which will then be moved from  into this sheet
'
lcopylastrow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row

lRRLastRow = wsRR.Cells(wsRR.Rows.Count, "A").End(xlUp).Offset(1).Row

' Unmerging cells within download
'
    ActiveWorkbook.Worksheets(1).Range("A3:G" & lcopylastrow).UnMerge

' This section of code will introduce the copy and pasting necessary to get the data into the consolidation of the report. As the report can only handle two separate Copy and pastes at a time, this first section will focus on getting the correct data sets for the left most columns (Sales & Cases)
'

wsCopy.Range("A8:D" & lcopylastrow).Copy _
    wsRR.Range("C" & lRRLastRow)

wsCopy.Range("E8:E" & lcopylastrow).Copy _
    wsRR.Range("AR" & lRRLastRow)

wsCopy.Range("F8:F" & lcopylastrow).Copy _
    wsRR.Range("AR" & lRRLastRow)

wsCopy.Range("G8:G" & lcopylastrow).Copy _
    wsRR.Range("AR" & lRRLastRow)

End Sub

A: I will add to this answer and continue to improve it as I better understand your objectives.
When aggregating data into an existing table, a common and advisable strategy is to go row by row. That way, you can search the table to see if the record already exists, and you can either add to the existing record, overwrite it, or skip it.
I have written up an example of how you might go row by row with your files:
Sub Example()
    Dim wsCopy As Worksheet
    Dim wsRR As Worksheet
    Dim wsRRPiv As Worksheet
    Dim lcopylastrow As Long
    Dim lRRLastRow As Long

    'Setting variables for report support workbook as well as download
    '

    Set wsCopy = ActiveWorkbook.Worksheets(1)
    Set wsRR = ThisWorkbook.Worksheets("Data")
    Set wsRRPiv = ThisWorkbook.Worksheets("Pivot")

    lcopylastrow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row

    lRRLastRow = wsRR.Cells(wsRR.Rows.Count, "A").End(xlUp).Offset(1).Row

    ' Unmerging cells within download
    '
      wsCopy.Range("A3:G" & lcopylastrow).UnMerge

    ' This section of code will introduce the copy and pasting necessary to get the data into the consolidation of the report. As the report can only handle two separate Copy and pastes at a time, this first section will focus on getting the correct data sets for the left most columns (Sales & Cases)
    '

    Const wsCopy_STARTING_ROW As Integer = 6 'First row containing data in wsCopy
    Const wsRR_STARTING_ROW As Integer = 5 'First row containing data in wsRR

    Dim i As Long
    For i = wsCopy_STARTING_ROW To lcopylastrow
        'For each row of data in wsCopy

        'save a reference to the current row
        Dim CurrentRow As Range
        Set CurrentRow = wsCopy.Rows(i)

        'Grab all data values from the current row
        'ASSUMES DATA IS IN COLUMNS 1 to 7 (A:G)
        Dim CustomerID As String, CostCenter As String, ProductID As String, ProductName As String, WSV As String, LBS_Sold As String, Tubes_Sold As String
        CustomerID = CurrentRow.Cells(1).Value
        CostCenter = CurrentRow.Cells(2).Value
        ProductID = CurrentRow.Cells(3).Value
        ProductName = CurrentRow.Cells(4).Value
        WSV = CurrentRow.Cells(5).Value
        LBS_Sold = CurrentRow.Cells(6).Value
        Tubes_Sold = CurrentRow.Cells(7).Value

        'Try to find the destination row in wsRR using the CustomerID and ProductID
        Dim rDestination As Range
        Dim j As Long
        For j = wsRR_STARTING_ROW To lRRLastRow
            'For each row in wsRR
            'Compare the customerID and ProductID in wsRR to the ones from wsCopy
            'ASSUMES CUSTOMER ID is in wsRR COLUMN B and PRODUCT ID is in wsRR COLUMN D
            If wsRR.Cells(j, 2) = CustomerID And wsRR.Cells(j, 4) = ProductID Then
                Set rDestination = wsRR.Rows(j)
                Exit For
            End If
        Next
        If rDestination Is Nothing Then
            'If no destination row was found, add it to the bottom of wsRR
            Set rDestination = wsRR.Rows(lRRLastRow)
            'ASSUMES CUSTOMER ID to PRODUCT DESCRIPTION ARE IN wsRR COLUMNS B:E
            rDestination.Cells(2) = CustomerID
            rDestination.Cells(3) = CostCenter
            rDestination.Cells(4) = ProductID
            rDestination.Cells(5) = ProductName
            lRRLastRow = lRRLastRow + 1
        End If

        'At this point we have all the data from wsCopy and we have identified a destination row in wsRR
        'I don't know what to put in "METRIC" or what to do with Walled Sales Value, Sales Pounds, Tubes Sold
        'You can do stuff like
        'rDestination.Cells(1) = "WSV"
        'rDestination.Cells(10) = CDbl(WSV)
        'Which would put the string "WSV" in column A and then put the Walled Sales Value as a number into column J
    Next
End Sub


text:
Q: How to access an ArrayList in an ArrayList? Java First let me tell you what I want to do.
The program should ask for a password and then create array lists for each character of the password.
These list will then be added to the overall array list.(mylist)
The question is how do I then populate the ArrayLists with String values?
When all the Arraylists are populated i want to be able to sort them in Alphabetical order.
Code blow.
// Creating ArrayLists
ArrayList<ArrayList<String>> mylist = new ArrayList<ArrayList<String>>();
List<String> mycode = new ArrayList<String>();
char[] test;
String mypassword;

System.out.println("Pleaseinput your passphrase");
        // Getting user input (Password)
        Scanner in = new Scanner(System.in);
        mypassword = in.nextLine();
        // Storing password in character array
        test= mypassword.toCharArray();

    // Beginning for loop to create array lists for each character
    // in the password
    for (int i = 0; i < mypassword.length(); i++) {
            mycode = new ArrayList<String>();
            // Here I'm trying to give the created Arraylist (mycode)
            // a name or value of the character the for loop is at so I                  can order it alphabetically later.
            mycode.equals(test[i]);
            // Adds the array list.
            mylist.add((ArrayList<String>) mycode);
        }

Thanks in advance for any suggestions on my question.

A: Assuming from the comments, you only want to transform a String into a List<String> where each character is a String, but want to have each character as the first element in a list and "hello" as the second element when the character is q...
public static void main(String[] args) {
    // Creating ArrayLists
    List<List<String>> mylist = new ArrayList<>();
    String mypassword;

    System.out.println("Pleaseinput your passphrase:");
    // Getting user input (Password)
    Scanner in = new Scanner(System.in);
    mypassword = in.nextLine();

    // Beginning for loop to create array lists for each character
    // in the password
    for (int i = 0; i < mypassword.length(); i++) {
        List<String> firstCharAndMore = new ArrayList<>();
        char c = mypassword.charAt(i);
        firstCharAndMore.add(String.valueOf(c));
        if ('q' == c) {
            firstCharAndMore.add("hello");
        }
        mylist.add(firstCharAndMore);
    }
    System.out.println(mylist.toString());
}

Input qwertyqwerty
Output: [[q, hello], [w], [e], [r], [t], [y], [q, hello], [w], [e], [r], [t], [y]]


text:
Q: Using position is good practice or not Can someone please guide me whether using positioning in css is good practice or not and will it creates problem when we are working on responsive design...

A: Check this explained in detail:

https://css-tricks.com/forums/topic/rwd-can-we-use-position-absolute-or-fixed-in-responsive/

A: It is necessary in some cases.
position: relative; // relative position of the parent.

position: relative gives the default behavior of the element. However, it is required if you want to have child element with position: absolute; in order to have specific position inside. Otherwise, the child element will position with any closest parent with position attribute.
position: absolute; // absolute position of the parent

position: absolute; needs its parent to have position attribute, too. Otherwise, top, left, right, bottom attributes will have unexpected results.
position: fixed; // fixed position of the document

position: fixed; stays at fixed position in the document.
z-index won't have effect if you don't have position attribute.


text:
Q: How to get a value from a nested dict? Is there an easy, concise way to get a value from a nested dict and get None if it's not there?
d1 = None
d2 = {}
d3 = {"a": {}}
d4 = {"a": {"b": 12345}}
ds = [d1, d2, d3, d4]

def nested_get(d):
    # Is there a simpler concise one-line way to do exactly this, query a nested dict value, and return None if
    # it doesn't exist?
    a_val = d.get("a") if d else None
    b_val = a_val.get("b") if a_val else None
    return b_val

if __name__ == "__main__":
    bs = [nested_get(d) for d in ds]
    print("bs={}".format(bs))

A: This should work:
def nested_get(d, *keys):
    for key in keys:
        if d is None:
            break
        d = d.get(key)
    return d

A: OK, using a simple custom function, I can do this, as a general concise solution:
d1 = None
d2 = {}
d3 = {"a": {}}
d4 = {"a": {"b": 12345}}
ds = [d1, d2, d3, d4]

def get_nested_dict_value(d, *args):
    for a in args:
        d = d.get(a) if d else None
    return d

if __name__ == "__main__":
    bs = [get_nested_dict_value(d, "a", "b") for d in ds]
    print("bs={}".format(bs))

A: If you want to get a little dirty, you can create a custom class that extends how a typical dictionary handles subscripting.
class QueryDict(dict):
    def __getitem__(self, keys):
        current = self
        try:
            for key in keys:
                current = dict.__getitem__(current, key)
            return current
        except (TypeError, KeyError):
            return None

d = {"a": {"b": {"c": 12345}}}
d = QueryDict(d)
print d['a','b','c'] # 12345
print d['a,c,e'] # None

Or, if you're trying to dynamically call entries, it might be better to allow keys to be passed in by a comma-separated string.
class QueryDict(dict):
    def __getitem__(self, key_string):
        current = self
        try:
            for key in key_string.split(','):
                current = dict.__getitem__(current, key)
            return current
        except (TypeError, KeyError):
            return None

d = {"a": {"b": {"c": 12345}}}
d = QueryDict(d)
print d['a,b,c'] # 12345.
print d['a,c,e'] # None

A: If you'd rather specify your "path" into the nested dict as a string path (like a directory) rather than a set of individual keys, this has worked for our needs:
def deep_get(d, path, default=None):
    """Get a deeply nested value in a dict based on multiple keys

    :param d: The dictionary
    :param path: The key path to search separated by '/'
    :param default: The default value to return if there is nothing
    :returns: The value at the given path or the default
    """
    dd = d
    split = path.split("/")
    for i, key in enumerate(split):
        try:
            dd = dd.get(key, {})
        except AttributeError as exc:
            p = "/".join(split[0:i])
            raise AttributeError("{} at {}".format(exc.message, p)), \
                None, sys.exc_info()[2]
    return dd or default

where the usage is as simple as
d = {
  'a': {
    'b': {
      'c': {
        'd': "hi!"
      }
    }
  }
}

print deep_get(d, 'a/b/c/d')


text:
Q: Deleting an element form vector of type structure I am trying this piece of code where I want to delete an element from the vector of type structure
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct _list
{
    int x;
}list;

std::vector<list> v;
list li[5];

void PushElements()
{
    for(int i = 0; i < 5; i++)
    {
        li[i].x = i+2;
        v.push_back(li[i]);
    }
}

void display()
{
    for(int i = 0; i < v.size(); i++)
    {
        cout << v[i].x << endl;
    }
}

bool test()
{
    int flag = false;
    for(int i = 0; i < 5; i++)
    {
        if(li[i].x < 3)
             flag = true;
    }
    return flag;
}

void DeleteElement()
{
    v.erase(remove_if(v.begin(), v.end(), test), v.end());
}

int main()
{
    PushElements();
    display();
    DeleteElement();

    return 0;
}

But while compiling I get the foolowing error:
 c:\program files (x86)\microsoft visual studio 9.0\vc\include\algorithm(1241) : error C2197: 'bool (__cdecl *)(void)' : too many arguments for call
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\algorithm(4951) : see reference to function template instantiation '_OutIt std::_Remove_copy_if<std::_Vector_iterator<_Ty,_Alloc>,_OutIt,bool(__cdecl *)(void)>(_InIt,_InIt,_OutIt,_Pr,std::_Range_checked_iterator_tag)' being compiled
1>        with
1>        [
1>            _OutIt=std::_Vector_iterator<list,std::allocator<list>>,
1>            _Ty=list,
1>            _Alloc=std::allocator<list>,
1>            _InIt=std::_Vector_iterator<list,std::allocator<list>>,
1>            _Pr=bool (__cdecl *)(void)
1>        ]
1>        c:\program files (x86)\microsoft visual studio    9.0\vc\include\algorithm(1311) : see reference to function template instantiation '_OutIt stdext::unchecked_remove_copy_if<std::_Vector_iterator<_Ty,_Alloc>,_FwdIt,bool(__cdecl *)(void)>(_InIt,_InIt,_OutIt,_Pr)' being compiled
1>        with
1>        [
1>            _OutIt=std::_Vector_iterator<list,std::allocator<list>>,
1>            _Ty=list,
1>            _Alloc=std::allocator<list>,
1>            _FwdIt=std::_Vector_iterator<list,std::allocator<list>>,
1>            _InIt=std::_Vector_iterator<list,std::allocator<list>>,
1>            _Pr=bool (__cdecl *)(void)
1>        ]

I am not able to understand what this error is and how to solve?
Can somebody help me in solving this error??

A: std::remove_if expects the signature of the predicate function should be equivalent to
bool pred(const Type &a);

But bool test() doesn't take any parameter, it doesn't match. You might want
bool test(const list& v)
{
    // judgement process based on the individual element passed
    // ...
}

A: I was very confused the author want to do.if you want to a program to add or remove some number you may erase many lines;
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct _list
{
    int x;
  _list(int x)
    {
        this->x=x;
    }
}list;

std::vector<list> v;
void PushElements()
{
    for(int i = 0; i < 5; i++)
    {

        v.push_back(list(i+2));//the number you want to add
    }
}
void display()
{
    for(int i = 0; i < v.size(); i++)
    {
        cout << v[i].x << "\t";
    }
    cout<<endl;
}

bool test(list &a)
{

    return a.x>3;
}

void DeleteElement()
{
    v.erase(remove_if(v.begin(), v.end(), test), v.end());
}

int main()
{
    PushElements();
    display();
    DeleteElement();
     display();
    return 0;
}


text:
Q: How to get Object from HttpResponse? I'm trying to send an object from server to client.
client side:
HttpResponse response = client.execute(request);

server side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws  IOException
{
    PrintWriter out = response.getWriter();
    out.print(new Object());
}

How do I get the object from the response?
Do i need to use instead:
OutputStream out = response.getOutputStream();

if so which way is more efficient?
example code please :)
thanks.

A: You cant just send Object.toString() because it does not contain all information about the object.
Serialisation is probably what you need. Take a look at that: http://java.sun.com/developer/technicalArticles/Programming/serialization/
The Object you want to send has to implement Serializable.
On your server you can then use something like this:
OutputStream out = response.getOutputStream();
oos = new ObjectOutputStream(out);
oos.writeObject(yourSerializableObject);

On the client side you do:
in = new ObjectInputStream(response.getEntity().getContent()); //Android
in = new ObjectInputStream(response.getInputStream()); //Java
ObjcetClass obj = (ObjectClass)in.readObject();


text:
Q: Monotouch: Universal app? Does Monotouch support the iPhone/iPad "universal app"?  If so, where can I find the docs on how to do it?

A: Yes, of course! Miguel De Icaza has done a very good job with Monotouch.
Under Project settings, select IPhone Application and then specify the target for your application: IPad only, IPhone only or both.
Rembember that when you want to create an universal app, you have to provide specific sizes for each device (views, orientations,images and so on).
To check the current device and customize your app for iPad and iPhone you can use the following property and verify if it contains ipad string. You can create a global boolean variable (a static variable for example and check the if your app is running on iPhone or iPad). To test run with the right simulator: obviously iPhone or iPad simulator.
UIDevice.CurrentDevice.Model

Cheers.


text:
Q: pip3 command fails after upgrading to pip version 18.1 After upgrading pip3 using $ pip3 install --upgrade pip, pip3 fails to work.  And throws this:
Error Command:
Traceback (most recent call last):
      File "/usr/bin/pip3", line 9, in <module>
        from pip import main
    ImportError: cannot import name 'main'

it's having the same issue again even after removing the pip3 and reinstalling it.
Somewhere someone suggested to change the from pip import main to from pip._internal import main. But still it didn't work.

A: As a general rule, it's best to leave your OS's Python installation alone, as it can be used for system dependencies. Install a clean version of Python with pyenv, and/or use virtualenv/Pipenv for development.
The pip3 command in the stack trace is in the system's binary path, and thus was probably installed by your operating system's package manager. It will be expecting an older version of pip, which you've removed by upgrading it.
As a temporary workaround, try running /usr/local/bin/pip3.


text:
Q: How to revert process file in FilePond JS? I started using Filepond JS and I am confused about how to call certain functions. Perhaps it is because my knowledge of ES6 is not that good, or maybe I am just overthinking this whole problem. The process uploads a file to a tmp folder. On the other hand, revert should remove the uploaded file from the tmp folder.
The Problem: I cannot seem to revert an upload in filepond.
Things I tried:

*

*Passing POST request with uniqueFileId

*Passing DELETE request with uniqueFileId

*Passing empty DELETE request

Any help is appreciated.
My JS:
//File upload
FilePond.registerPlugin(
   FilePondPluginFileValidateSize,
   FilePondPluginFileValidateType,
   FilePondPluginFileEncode
);

const inputElement = document.querySelector("input[type='file']");

file = FilePond.create(
   inputElement,
   {
      credits: false,
      maxFileSize: "3000000",
      acceptedFileTypes: [
         'image/jpeg',
         'image/png',
         'application/pdf',
      ],
      fileValidateTypeDetectType: (source, type) => new Promise((resolve, reject) => {
            resolve(type);
      }),
      server: {
         process:(fieldName, file, metadata, load, error, progress, abort, transfer, options) => {

            // fieldName is the name of the input field
            // file is the actual file object to send
            const formData = new FormData();
            formData.append(fieldName, file, file.name);

            const request = new XMLHttpRequest();
            request.open('POST', secureUrl("Model/filepond/index.php"));

            // Should call the progress method to update the progress to 100% before calling load
            // Setting computable to false switches the loading indicator to infinite mode
            request.upload.onprogress = (e) => {
               progress(e.lengthComputable, e.loaded, e.total);
            };

            // Should call the load method when done and pass the returned server file id
            // this server file id is then used later on when reverting or restoring a file
            // so your server knows which file to return without exposing that info to the client
            request.onload = function() {
               if (request.status >= 200 && request.status < 300) {
                  // the load method accepts either a string (id) or an object
                  load(request.responseText);
               }
               else {
                   // Can call the error method if something is wrong, should exit after
                   error('oh no');
               }
            };

            request.send(formData);

            // Should expose an abort method so the request can be cancelled
            return {
               abort: () => {
                  // This function is entered if the user has tapped the cancel button
                  request.abort();

                  // Let FilePond know the request has been cancelled
                  abort();
               }
            };
         },
         revert: (uniqueFileId, load, error) => {

            const formData = new FormData();
            formData.append(uniqueFileId);

            const request = new XMLHttpRequest();
            request.open('DELETE', secureUrl("Model/filepond-server-php-master/index.php"));

            request.send(formData);

            // Can call the error method if something is wrong, should exit after
            error('oh my goodness');

            // Should call the load method when done, no parameters required
            load();
          }
        }
      }
    );

I looked in the FilePond.class.php:
// revert existing transfer
if ($request_method === 'DELETE') {
   return call_user_func($routes['REVERT_FILE_TRANSFER'], file_get_contents('php://input'));
}

A: I found that the server can be simplified to the following which allows us to revert the upload. I am not sure why the other way was not working but seems to work just fine.
My JS simplified:
//File upload
FilePond.registerPlugin(
   FilePondPluginFileValidateSize,
   FilePondPluginFileValidateType,
   FilePondPluginFileEncode
);

const inputElement = document.querySelector("input[type='file']");

file = FilePond.create(
   inputElement,
   {
      credits: false,
      maxFileSize: "3000000",
      acceptedFileTypes: [
         'image/jpeg',
         'image/png',
         'application/pdf',
      ],
      fileValidateTypeDetectType: (source, type) => new Promise((resolve, reject) => {
            resolve(type);
      }),
      server: {
         url: secureUrl("Model/filepond/index.php"),
         process: './process',
         revert: './revert',
         restore: './restore/',
         load: './load/',
         fetch: null
       }
   }
);


text:
Q: python copied list affects base list So in my free Time I've been trying to make a little Programm, however I've run into a slight problem. I want to change some things in a copied list, but for some reason the changes get caried over to the original/base list.
from random import *

a = [[0,5,9,5,9,4,0,0,5],
[0,0,7,0,0,3,0,0,3],
[0,0,5,0,0,0,7,8,45]]
b = a.copy()

for x in range(len(b)):
 for y in range(len(b[1])):
  if b[x][y] == 0:
   b[x][y] = randint(10, 100000)

if a == b:
 print("Not working")

print(b)
print(a)

I have also tried b = list(a) and with the copy library, but all my changes to b still get carried over to a, resulting in a == b being true.
Does someone know what the problem is or what I'm doing wrong/misunderstanding? Help would be very appreciated and thanks in advance.

A: You have a list of lists, thus you need to deepcopy a to avoid mutating a:
import copy

a = [[0,5,9,5,9,4,0,0,5],
[0,0,7,0,0,3,0,0,3],
[0,0,5,0,0,0,7,8,45]]
b = copy.deepcopy(a)

Short explanation: You copy the outer "structure" of list a, while the "inner structure" is still consisting of references to the "sub"-level lists. Thus the second level of b still refers to the same elements in a. copy.deepcopy avoids this problem by copying all mutable elements of an object down to a certain depth.

A: You must use deepcopy to copy everything, otherwise you copy only the top level list.
For example:
from random import *
from copy import deepcopy

a = [[0,5,9,5,9,4,0,0,5],
[0,0,7,0,0,3,0,0,3],
[0,0,5,0,0,0,7,8,45]]
#use this
b=deepcopy(a)
#instead of this
#b = a.copy()

for x in range(len(b)):
 for y in range(len(b[1])):
  if b[x][y] == 0:
   b[x][y] = randint(10, 100000)

if a == b:
 print("Not working")

print(b)
print(a)

You can read about the difference between shallow and deep copy in the official documentation.


text:
Q: How do I move a site from the top bar to the side bar I am trying to move a site from the top bar to appear in the side bar - how do I do that?

A: I am assuming you are using SharePoint 2010. Go to Site Actions - Site Settings. Under Look and feel you should see a Navigation link.
Under the Navigation Editing and Sorting section you can delete or hide the Site under Global Navigation (top) and add it to Current Navigation (side bar).


text:
Q: for $n\ge3$, every nontrivial normal subgroup of $S_n$ either contains a $3$-cycle or a product of two disjoint $2$-cycles Prove that for $n\ge3$, every nontrivial normal subgroup of $S_n$ either contains a $3$-cycle or a product of two disjoint $2$-cycles.
This question cannot directly use the advanced fact that $A_n$ is simple group for $n\ge5$ and classification of normal subgroup of $S_n$ ($n\ge 3$) like here.
My attempts:
A normal subgroup $N$ of $G$ is union of conjugacy classes, here.  The conjugacy class of $S_n$ should have same cycle type, here.
Conjugacy class itself is not closed in group multiplication. I want to prove that a normal subgroup generated by any conjugacy class of $S_n$ will contain a $3$-cycle or a product of two disjoint $2$-cycles.
That is to construct a $3$-cycle or a product of two disjoint $2$-cycles just by multiplying group element with same cycle type. However I don't have idea how to proceed, or is there other easy way to prove original problem?


text:
Q: Asynctask cant run twice I have a problem when I'm trying to run an AsyncTask several times. Here is my code:
btnonoff.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (btnonoff.isChecked()){
            new main_progress_doinbackground().execute();

                   }
            }
       });
   }

I want to execute the AsyncTask whenever I check the toggle button. The first time the code executes fine, but when I try to run it again, it's not working. I think it's because main_progress_doinbackground().execute(); can't stop. I tried to stop it manually but the problem exist...
This id my Asynctask code :
class main_progress_doinbackground extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... params) {
dodb();
return null;

dodb() get some gps locations and if they are near the device , it began to alarm .
new main_progress_doinbackground().cancel(true);
main_progress_doinbackground.cancel(true);

both not working .
I tried this but it's not working. When I use this code :
btnonoff.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (!btnonoff.isChecked()) {
        //      new main_progress_doinbackground().cancel(true);
                main_progress_doinbackground.cancel(true);

            }

        if (btnonoff.isChecked()){

        //new main_progress_doinbackground().execute();
         main_progress_doinbackground.execute();

I gave this error :

11-15 08:30:05.065: E/AndroidRuntime(1458):
  java.lang.IllegalStateException: Cannot execute task: the task is
  already running.

A: You have to define your AsyncTask object and cancel the specific one. Change your code like that:
main_progress_doinbackground myTask;
btnonoff.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            myTask = new main_progress_doinbackgroud;
            if (btnonoff.isChecked()){
            myTask.execute();

                   }
            }
       });
   }

And when you want to stop that task:
myTask.cancel(true);

Note: As an advice, follow good programming practices, change your class name main_progress_doinbackground to MainProgressTask. That turns your object definition into this:
MainProgressTask mainProgressTask;

A: I think the problem happens because you are calling the .execute() method over the same instance of your AsynckTask, and you can't do this.
More exactly:
wrong way
// only one instance
MyAsinchTask myAsynchTask = new MyAsinchTask();

myAsynchTask.execute();
myAsynchTask.execute();

correct way
// two different instances
MyAsinchTask myAsynchTask = null;

myAsynchTask = new MyAsinchTask();  // first instance
myAsynchTask.execute();

myAsynchTask = new MyAsinchTask();  // second instance
myAsynchTask.execute();             // error!

try to correct your code, making sure you create a new instance every time you invoke the execute() method.
P.S.: read this simple article about code and naming convention in Java! It's very important!
basic Java code convention


text:
Q: microsoft teams get conversation link I am using Microsoft team integration using nodejs. In the Teams client you can easily copy a link to the conversation and this can be used to navigate to the specific conversation any time.
see the screenshot for the reference: https://www.dropbox.com/s/fog3ojddcb6mdis/screen%20shot%202021-02-10%20at%202.44.31%20pm.png?dl=0
Is there a way to get this link in the botframework when the conversation is created? I have seen there are deep link apis for group chat etc. which requires the list of users to be provided.
but I am interested in obtaining the conversation link that appears on client.
This one is not useful https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links
The activity object I get in nodejs on starting a conversation is:
{
  "localTimestamp": "2021-02-13T05:42:25.313Z",
  "timestamp": "2021-02-13T05:42:25.313Z",
  "type": "message",
  "locale": "en-US",
  "from": {
    "name": "Stacy",
    "id": "29:1a-Xb7uPrMwF2XqjMEHCC7ytV2xb2VUCqTA-n_s-k5ZyMCTKIL-ku2XkgbE167D_5ZbmVaqQxJGIQ13vypSqu-A",
    "aadObjectId": "718ab805-850c-43ec-8d4e-4af0c543df75"
  },
  "serviceUrl": "https://smba.trafficmanager.net/amer/",
  "conversation": {
    "isGroup": true,
    "conversationType": "channel",
    "id": "19:a0a0088174a644cb91406f4d8f79d888@thread.tacv2;messageid=1613194945273",
    "tenantId": "04e934f3-0866-4a6d-b07c-a4737e8f9865"
  },
  "localTimezone": "America/Los_Angeles",
  "recipient": {
    "name": "MyBot",
    "id": "28:a835cf1d-83a8-5ae9-845a-23a68a1df442"
  },
  "id": "1613194445273",
  "channelData": {
    "channel": {
      "id": "19:a0a0088174a644cb91459f4d8f79d888@thread.tacv2"
    },
    "tenant": {
      "id": "04e930f3-0866-4a6d-c07c-a4737e8f9865"
    },
    "team": {
      "id": "19:774d4103fe51420db1437130378b196e@thread.tacv2"
    },
    "teamsChannelId": "19:a0a0088174a644cb91409f5d8f79d888@thread.tacv2",
    "teamsTeamId": "19:774d4103fe51420db1437190478b196e@thread.tacv2"
  },
  "attachments": [
    {
      "contentType": "text/html",
      "content": "

MyBot opty
\n
"
    }
  ],
  "textFormat": "plain",
  "channelId": "msteams",
  "entities": [
    {
      "text": "<at>MyBot</at>",
      "mentioned": {
        "id": "28:a835cf1d-83a8-4ae9-845a-23a68a1df432",
        "name": "MyBot"
      },
      "type": "mention"
    },
    {
      "country": "US",
      "platform": "Mac",
      "timezone": "America/Los_Angeles",
      "locale": "en-US",
      "type": "clientInfo"
    }
  ],
  "text": "opty"
}

A: You can use Get Chat Graph API
POST: https://graph.microsoft.com/beta/me/chats
These permission needs to be given at delegated level to the Application
Chat.ReadBasic, Chat.Read, Chat.ReadWrite
You can will be able to see chatType/Topic base on that you can get the chatId and pass it to Get Message in Chat,
So in the end you can use the deep link and create deep link to chat using
https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links#generating-a-deep-link-to-a-chat
Note: While creating deep link to specific message in group chat, you should have the group chat id and message id. Message Id you can get it within Bot activity and use it later to create deep link.

A: For anyone wondering how to do deep linking to an existing group chat, you'd need to have the chatId.
The URL is as follows:
https://teams.microsoft.com/l/chat/{chatId}/0?tenantId={tenantId}


text:
Q: How to create initializer to create and migrate mysql database? I have been learning how to use EF for a week or so now and am stuck on the issue of creating/updating my database. I am able to create an initializer to create the database if it is not there:
static class Program
{
    static void Main()
    {
        Database.SetInitializer<GumpDatabase>(new GumpDatabaseInitializer());
....

class GumpDatabaseInitializer : CreateDatabaseIfNotExists<GumpDatabase>
{
    public GumpDatabaseInitializer()
    {
    }
    protected override void Seed(GumpDatabase context)
    {
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX Name ON Stations (Name)");
        // Other stuff
    }
}

Or I can create a Configuration to migrate the db
static class Program
{
    static void Main()
    {
        Database.SetInitializer<GumpDatabase>(new MigrateDatabaseToLatestVersion<GumpDatabase, Configuration>());
....

internal sealed class Configuration : DbMigrationsConfiguration<GumpDatabase>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
    }

    protected override void Seed(GumpDatabase context)
    {

    }

Each works correctly but I haven't figured out a way to do both. I can switch between the two initializers by changing the SetInitializer call but if I want to create the database if it is not there and also migrate it if it is what do I do?  Do I need to create a custom initializer?
Thanks
Edit based on NSGaga answer
class CreateOrMigrateDatabaseInitializer<TContext, TConfiguration> : CreateDatabaseIfNotExists<TContext>, IDatabaseInitializer<TContext>
    where TContext : DbContext
    where TConfiguration : DbMigrationsConfiguration<TContext>, new()
{
    private readonly DbMigrationsConfiguration _configuration;
    public CreateOrMigrateDatabaseInitializer()
    {
        _configuration = new TConfiguration();
    }
    public CreateOrMigrateDatabaseInitializer(string connection)
    {
        Contract.Requires(!string.IsNullOrEmpty(connection), "connection");

        _configuration = new TConfiguration
        {
            TargetDatabase = new DbConnectionInfo(connection)
        };
    }
    void IDatabaseInitializer<TContext>.InitializeDatabase(TContext context)
    {
        Contract.Requires(context != null, "context");

        if (context.Database.Exists())
        {
            if (!context.Database.CompatibleWithModel(throwIfNoMetadata: false))
            {
                var migrator = new DbMigrator(_configuration);
                migrator.Update();
            }
        }
        else
        {
            context.Database.Create();
            Seed(context);
            context.SaveChanges();
        }

    }
    protected virtual void Seed(TContext context)
    {
    }
}

and
internal sealed class Configuration : DbMigrationsConfiguration<GumpDatabase>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
        SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
    }

    protected override void Seed(GumpDatabase context)
    {
    }
}

and
class GumpDatabaseInitializer : CreateOrMigrateDatabaseInitializer<GumpDatabase,Gump.Migrations.Configuration>
{
    public GumpDatabaseInitializer()
    {
    }
    protected override void Seed(GumpDatabase context)
    {
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX Name ON Stations (Name)");
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX Name ON Sequences (Name)");
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX StationPartNumber ON StationPartNumbers (StationId,PartNumberId)");
    }
}

and finally
static void Main()
{
    Database.SetInitializer<GumpDatabase>(new GumpDatabaseInitializer());

A: I think you're pretty much there - you can lookup the source code for MigrateDatabaseToLatestVersion (it's open source http://entityframework.codeplex.com/) - it's pretty simplistic, what it does pretty much is call the DbMigrator - as far as I could see.
All you have to do seems is to merge the two - use one or the other as a basis, add other functionality in there - that should work fine I think.
class CreateAndMigrateDatabaseInitializer<TContext, TConfiguration> : CreateDatabaseIfNotExists<TContext>, IDatabaseInitializer<TContext>
    where TContext : DbContext
    where TConfiguration : DbMigrationsConfiguration<TContext>, new()
{
    private readonly DbMigrationsConfiguration _configuration;
    public CreateAndMigrateDatabaseInitializer()
    {
        _configuration = new TConfiguration();
    }
    public CreateAndMigrateDatabaseInitializer(string connection)
    {
        Contract.Requires(!string.IsNullOrEmpty(connection), "connection");

        _configuration = new TConfiguration
        {
            TargetDatabase = new DbConnectionInfo(connection)
        };
    }
    void IDatabaseInitializer<TContext>.InitializeDatabase(TContext context)
    {
        Contract.Requires(context != null, "context");

        var migrator = new DbMigrator(_configuration);
        migrator.Update();

        // move on with the 'CreateDatabaseIfNotExists' for the 'Seed'
        base.InitializeDatabase(context);
    }
    protected override void Seed(TContext context)
    {
    }
}

call it like this...
Database.SetInitializer(new CreateAndMigrateDatabaseInitializer<GumpDatabase, YourNamespace.Migrations.Configuration>());

...actually, override it (since it's generic implementation) like you were doing for CreateDatabaseIfNotExists (you just have extra 'param' for Configuration)  - and just supply the 'Seed'.
class GumpDatabaseInitializer : CreateAndMigrateDatabaseInitializer<GumpDatabase, YourNamespace.Migrations.Configuration>
{
    protected override void Seed(GumpDatabase context)
    {
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX Name ON Stations (Name)");
    }
}

...and call it something like
Database.SetInitializer(new GumpDatabaseInitializer());

EDIT:
Based on the comments - DbMigrator should not run twice. It always checks (spends a bit of time) and does a 'blank' update and moves on. However just in case if you'd like to remove that and 'check' before entering - this should work (change the similar piece above)...
var migrator = new DbMigrator(_configuration);
if (!context.Database.CompatibleWithModel(throwIfNoMetadata: false))
    if (migrator.GetPendingMigrations().Any())
        migrator.Update();

(this is a redundant / double-check - one of the if-s should be enough. Put a break there - and see exactly what's happening, it should not get in - once Db is migrated. As I mentioned, works fine when I test it.
EDIT:
Replace the inside of InitializeDatabase with...
var doseed = !context.Database.Exists();
// && new DatabaseTableChecker().AnyModelTableExists(context);
// check to see if to seed - we 'lack' the 'AnyModelTableExists' - could be copied/done otherwise if needed...

var migrator = new DbMigrator(_configuration);
// if (doseed || !context.Database.CompatibleWithModel(throwIfNoMetadata: false))
    if (migrator.GetPendingMigrations().Any())
        migrator.Update();

// move on with the 'CreateDatabaseIfNotExists' for the 'Seed'
base.InitializeDatabase(context);
if (doseed)
{
    Seed(context);
    context.SaveChanges();
}

This works around (half-way) not-seeding - if migration goes first. And migrations have to be first, otherwise you have issues.
You still need to do it properly - this is the gist if not all you might need - but if any issues w/ MySQL etc., probably some more leg work here.
Note: Still seeding doesn't call if you have a db, but it's empty. Problem is mixing of the two different initializers. So you'll have to work that out - either by implementing what Create... does inside (that call we can't call) or something else.

A: Actually it should be:
var migrator = new DbMigrator(_configuration);
if (!context.Database.CompatibleWithModel(false) || migrator.GetPendingMigrations().Any())
    migrator.Update();

because if we have a migration, that is not related to our db model, for example inserting a row in any of our tables, the migration won't be executed.

A: To do both (seed and migrate) you really only have to use migrations with a MigrateDatabaseToLatestVersion initializer. When you enable migrations for your context a Configuration class derived from DbMigrationsConfiguration is created and you can override the Seed method to seed your database. Note that the database may already contain seed data when this method executes but the AddOrUpdate extension method conveniently helps you make "upserts" in your database.
This is different compared to the Seed method of some of the other database intitializers where the database is only seeded when it is initially created. However, when you are using migrations you may want to change your seed data when the database changes and using MigrateDatabaseToLatestVersion makes that possible.
To combine seeding with migrations you will have to perform the following steps in a new project:

*

*Create a code-first DbContext with associated entities

*In the package manager console execute the command Enable-Migrations

*In the Migrations folder a Configuration class is generated with a Seed method. You can modify this method to seed your database:
protected override void Seed(MyContext context) {
  // Add two entities with name "Foo" and "Bar".
  context.MyEntities.AddOrUpdate(
    e => e.Name,
    new MyEntity { Name = "Foo" },
    new MyEntity { Name = "Bar" }
  );
}

*You need to create a database initializer that derives from MigrateDatabaseToLatestVersion:
class MyContextInitializer
  : MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration> { }

You will also have to configure the initializer either by calling Database.SetInitializer(new MyContextInitializer()) when you application starts or in the App.config file by using the <databaseInitializer/> element.

*In the constructor for the generated Configuration class you can enable automatic migrations:
public Configuration() {
  AutomaticMigrationsEnabled = true
}

However, in a team you might prefer to not do that. In that case you will have to create an initial migration (unless it was created when you did Enable-Migrations). In the package manager execute the command Add-Migration InitialCreate. This creates the first migration required to create your database.
At this point you have a DbContext with migrations and a Seed method.
So to sum it: Enable migrations, use the MigrateDatabaseToLatestVersion initializer and add seed data in the Configuration class that was generated when migrations were enabled.

A: While MigrateDatabaseToLatestVersion does actually create the DB if it does not exist and even allows you to seed it, if you already have a working solution based on CreateDatabaseIfNotExists and/or don't want to complicate it with testing for existence of seed data, you can just use the below by inheriting from it rather than from CreateDatabaseIfNotExists:
public class CreateOrMigrateDatabaseInitializer<TContext, TConfiguration> : CreateDatabaseIfNotExists<TContext>, IDatabaseInitializer<TContext>
        where TContext : DbContext
        where TConfiguration : DbMigrationsConfiguration<TContext>, new()
    {

        void IDatabaseInitializer<TContext>.InitializeDatabase(TContext context)
        {
            if (context.Database.Exists())
            {
                if (!context.Database.CompatibleWithModel(throwIfNoMetadata: false))
                {
                    var migrationInitializer = new MigrateDatabaseToLatestVersion<TContext, TConfiguration>(true);
                    migrationInitializer.InitializeDatabase(context);
                }
            }

            base.InitializeDatabase(context);
        }
    }

This is based on previous answers and OP's own solution. This should work with other providers as well, but I only tested with SQL Server.


text:
Q: git checkout only the folder, no files Windows is able to handle case-sensitive files by using this command on folders:
fsutil.exe file setCaseSensitiveInfo "C:\examplefolderpath" enable

However, the issue with this is that it doesn't automatically apply to subfolders... There is a way to apply it to subfolders using PowerShell, but they have to actually exist first. Thus, I'm looking for a way to retrieve a git repo's folder structure without actually downloading any of its files. Only after the folder structureis created and I've run the PowerShell command do I want to checkout the files.
Is there a convenient way to do this using git commands alone?
If not, is there a way for PowerShell to retrieve the folder structure from a bare git repository (using git clone --bare) and setup the folder structure? (For a side-project I'm working on, it would also be useful to know how to do this using Go, unless git commands alone can do it. But, this isn't as important as knowing how to do it with PowerShell.)

A: Git doesn't provide a way to check out only the directories and not the files.  You have some options, though:

*

*Use Git in WSL to create the repository, which according to this article will mean that they'll automatically be made case sensitive.

*Avoid running git checkout and find the file hierarchy with git ls-tree -rd HEAD (or whatever revision you want instead of HEAD), then generate those directories, and only then run git checkout.  However, note that PowerShell pipes are known to corrupt data passed through them, so this wouldn't be a good idea when working with Git.

If you want Git for Windows to support this natively, you could go over to their issue tracker and ask for this to supported natively as a feature.  I don't know how much work it would be, and I'm unable to find documentation for the API required, so it's unclear whether it could be reasonably implemented in Git.

A: With thanks to bk2204's answer for pointing me in the right direction... after creating a bare repo with ``, I can creature the directory structure with this function:
function Invoke-GitCloneCS {
  [Alias('igccs')]
  param([Parameter(Mandatory)] $url)

  # Terminate function if user isn't admin
  if (${env:=::}) { 'Function must be ran as administrator!'; return }

  # Normalize URL so the variable ends in .git
  $url = ("$url" -replace '.git$') -replace '$','.git'

  # Derive repo name from $url
  $repo = $url.Split('/')[-1] -replace '.git$'

  git clone $url --no-checkout

  # Navigate to repo directory and apply setCaseSensitiveInfo to it
  Set-Location $repo -pv D | & { fsutil.exe file setCaseSensitiveInfo $D enable }

  # Retrieve the folder structure
  (git ls-tree --name-only -rd HEAD).ForEach({
    # Create each folder listed, and apply setCaseSensitiveInfo to it
    New-Item $_ -Type D -pv D | & { fsutil.exe file setCaseSensitiveInfo $D enable }})

  git checkout
  Set-Location ..
}

Now, that isn't the complete command, I still need to work in all the


text:
Q: How do I count how many times a value has changed pertaining to a unique ID? I am trying to figure out how many times a student has changed majors over the course of their college career.
   Create Table Taco
  (  s_id  varchar(9),
     s_year  int,
     s_major varchar(50))

 Insert INTO Taco
 Values (123456789, 2018, 'PSYCHOLOGY'),
        (123456789, 2016, 'GENERAL EDUCATION'),
        (123456789, 2017, 'PSYCHOLOGY'),
        (987654321, 2018, 'FILM'),
        (987654321, 2017, 'ANTHROPOLOGY'),
        (654789123, 2018, 'BIOLOGY'),
        (654789123, 2017, 'BIOLOGY'),
        (987654321, 2015, 'COMPUTER SCIENCE')

I am expecting the result:
 s_id     changes
 123456789     2
 987654321     3
 654789123     1

How would I write this?

A: Use Count and GROUP BY
SELECT s_id,count(s_id) 'changes'
FROM Taco
group by s_id

sqlfiddle:http://sqlfiddle.com/#!18/2c1d7/2

A: To get the number of real changes you can use LAG function to receive the last value within a group (s_id) and sum up all differences between the previous value and the current value:
SELECT t.s_id
     , SUM(CASE WHEN t.prev_val <> t.s_major OR t.prev_val IS NULL THEN 1 END) as chg_cnt
FROM
   (
       SELECT s_id
             ,s_year
            , s_major
            , LAG(s_major) OVER(PARTITION BY s_id ORDER BY s_year) prev_val
       FROM Taco
    ) as t
GROUP BY s_id

extended sqlfiddle code: http://sqlfiddle.com/#!18/61048/11

A: You can just count the entries in your table and substract one to determine the amount of changes for each student.
SELECT
  s_id,
  COUNT(s_id) - 1 AS [Amount of changes]
FROM
  Taco
GROUP BY
  s_id

I would also recommend changing the type of the last column to varchar(50) or something bigger.
See SQL fiddle: http://sqlfiddle.com/#!18/59ae2/1


text:
Q: Pre & post increment operator behavior in C, C++, Java, & C# DISCLAIMER: This is not a real-world example. It    is just a theoretical question of how    these languages work.
What exactly are the differences between C/C++, C#, and Java when it comes to post & pre increment operators?
This is what I get with VC++10, Java 1.6, and C# 4
int a = 2;
int b = a++ + a++;
int c = ++a + a++ + a++;

      +-----+------+------+----+
      |  C  | C++  | Java | C# |
+-----+-----+------+------+----+
| a   |  7  |  7   |   7  |  7 |
+-----+-----+------+------+----+
| b   |  4  |  4   |   5  | 5  |
+-----+-----+------+------+----+
| c   | 15  |  15  |  16  | 16 |
+-----+-----+------+------+----+

A: Java and C# evaluate expressions from left to right, and the side-effects are visible immediately.
In C++, the order of evaluation of subexpressions is unspecified, and modifying the same object twice without an intervening sequence point is undefined behavior.

A: In C++, this is undefined behaviour, so any answer would be correct. See Undefined behavior and sequence points for further details.
Not sure about other languages, but I would expect this code to be incorrect there, too.
EDIT:
See Eric Lippert's answer about C#. He disproves my assumption about C#'s behaviour.

A: In C++ at least this undefined behaviour.  Quoting the C++ standard:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

A: I don't have the time to write up a detailed description of the differences between C++, C, C# and Java. I will merely say that the C# behaviour of the pre and post increment operators is fully specified (in single-threaded scenarios; if you want to know about its atomicity, guarantees about observations of read and write orders in multi-processor weak memory models and so on, you're on your own to do that research.) It is not fully specified in C and C++; a compiler has broad lattitude to do whatever it pleases with re-ordering side effects. I have never used Java so I'm not going to hazard a guess as to what Java does.
For more information on what C# does you should read the C# specification. For a short take on it, read my answer to this question:
What is the difference between i++ and ++i?
For an even shorter take:
Subexpressions in a C# expression are logically grouped by precedence and associativity, and then evaluated from left to right regardless. (So for example, A() + B() * C() evaluates A(), then B(), then C(). The fact that the multiplication "comes before" the addition is irrelevant; the subexpressions are always evaluated left to right.)
If the evaluation of a subexpression causes a side effect because of a pre or post increment subexpression then the side effect happens immediately before the result is produced.

A: The Java memory model ensures the order the loads and stores are done, so it should come out the same on any JVM (I believe).
It looks like C++ has the same order of operations, but once you use it twice on a line you start running into other stuff (Vlad is right there). If you try other C++ compilers, you may find they come up with different answers.
I'm sure C# has the same order of operations, but my guess is they have a memory model (like Java) that ensures consistency, but I don't have a lot of knowledge here.

A: I like this question and found very good explanations but I just want to explain this question by it's value how it is evaluated:
I will only talk about java and c/C++ as I have no knoledge about C#
Statements are evaluated in following ways
In java
Statement |||||||||||||||||||||||||||||||||||||||||||||||||||||||          Trace
int a= 2;                     a=2
int b= a++ + a++;             a=2, a=3

here value of a=4

int c = ++a + a++ + a++;      a=5, a=5, a=6

here value of a=7

In C/C++
Statement               Trace
int a= 2;                     a=2
int b= a++ + a++;             a=2, a=2

here value of a=4

int c = ++a + a++ + a++;      a=5, a=5, a=5

here value of a=7

In short in java expression goes left to right so at the 2nd "a" it will fetch new value and in c/c++ it will first evaluate whole expression and then increment all operands of statement.


text:
Q: Dell Inspiron 1564 overheating but fan not switching on, how to diagnose? I've got a Dell Inspiron 1564 laptop that is about one and a half years old. Since about a week, the laptop started to overheat, causing it to switch off unexpectedly...
The cpu fan is working erratically, it can start to spin for a while, doing its job and cooling down the cpu before it stops, but then the temperature goes up, and the fan doesn't reacts, once the temperature reaches a critical point (over 85 celsius, checked with speedfan...), the laptop switches off...
I already cleaned the vents and fan from dust, to no avail, and it was actually quite clean anyway.
Drivers and bios are up-to-date, no crapware was ever installed on this machine.
I don't know how to diagnose the problem, could it be the temperature sensors that sends wrong information, so the fan doesn't reacts? but then I believe the computer wouldn't detect the overheat and stop...
Is there a way I can pin point the problem? Maybe some low-level diagnostic tools to check functionality of sensors and fans???
The warranty is already over so any suggestion would be welcome.
Thanks!!

A: I also had this problem in my Inspiron 1464. I removed the RAM and inserted again. After doing this I started my computer. The fan works well then.

A: Download and make the Dell diagnostic boot media, then boot from it and run the hardware extended tests.
.
Dell Main page for your model
.


text:
Q: Mysql Pivot table using codeigniter I need to generate report like pivot table in codeigniter. It is working in mysql PHPmyadmin but when I use in codeigniter it shows sql syntax error.
Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
SET @sql = CONCAT('SELECT sf.nc_name, sf.code, ', @sql, 'FROM sirform AS sf INNER JOIN rejection AS rb ON sf.id = rb.sir_id GROUP BY sf.nc_name'

Filename: C:\xampp\htdocs\rnaiplpqcms\system\database\DB_driver.php

Line Number: 331

 //Controller
 public function report(){
    $data['report'] = $this->user_model->report();
    $this->load->view("templates/header");
    $this->load->view("pivot_report",$data);
    $this->load->view("templates/footer");
  }

  //Model

   public function report(){
        $this->db->query("SET @sql = NULL");
        $this->db->query("SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(rb.model = ''',model,''', rb.quantity, NULL)) AS ',model)) INTO @sql FROM rejection");
        $this->db->query("SET @sql = CONCAT('SELECT sf.nc_name, sf.code, ', @sql, 'FROM sirform AS sf INNER JOIN rejection AS rb ON sf.id = rb.sir_id GROUP BY sf.nc_name'");
          $this->db->query("PREPARE stmt FROM @sql");
        $this->db->query("EXECUTE stmt");
        $this->db->query("DEALLOCATE PREPARE stmt");

        $query = $this->db->get();
        return $query->result_array();
      }

   //View

                 Code
                 Name
                 Quantity
                 Model

              <?php if(isset($report)) {
                foreach($report  as $reports){ ?>

                 <?php echo $reports['code']; ?>
                 <?php echo $reports['name']; ?>
                 <?php echo $reports['quantity']; ?>
                 <?php echo $reports['model']; ?>	// Model as header and quantity below it

                <?php }} ?>

  Code
  Name
  Model1
  Model2
  Model3

  123
  xyz
  2
  0
  2

  456
  abc
  5
  3
  0

A: why don't you convert the query to a stored procedure on mysql and execute the SP from codeigniter??

A: You did not closed parentheses of CONCAT method.
$this->db->query("SET @sql = CONCAT('SELECT sf.nc_name, sf.code, ', @sql, 'FROM sirform AS sf INNER JOIN rejection AS rb ON sf.id = rb.sir_id GROUP BY sf.nc_name')");


text:
Q: C - Forward declaration for struct and function I'm trying to figure out how exactly forward declarations interact. When forward declaring a function that takes a typedef'd struct, is there a way to just get the compiler to accept a previously forward declared (but not actually defined) struct as a parameter?
The code that I've got working:
typedef struct{
  int year;
  char make[STR_SIZE];
  char model[STR_SIZE];
  char color[STR_SIZE];
  float engineSize;
}automobileType;

void printCarDeets(automobileType *);

What I wish I could do:
struct automobileType;
void printCarDeets(automobileType *);

//Defining both the struct (with typedef) and the function later

I feel like I'm either missing something really basic or not understanding how the compiler deals with forward declarations of structs.

A: Typedefs and struct names are in different namespaces.  So struct automobileType and automobileType are not the same thing.
You need to give your anonymous struct a tag name in order to do this.
The definition in your .c file:
typedef struct automobileType{
  int year;
  char make[STR_SIZE];
  char model[STR_SIZE];
  char color[STR_SIZE];
  float engineSize;
}automobileType;

The declaration in your header file:
typedef struct automobileType automobileType;
void printCarDeets(automobileType *);


text:
Q: Common HTTPclient and proxy I am using apache's common httpclient library. Is it possible to make HTTP request over proxy? More specific, I need to use proxy list for multithreaded POST requests (right now I am testing with single threaded GET requests).
I tried to use:
        httpclient.getHostConfiguration().setProxy("67.177.104.230", 58720);

I get errors with that code:
21.03.2012. 20:49:17 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect
21.03.2012. 20:49:17 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
21.03.2012. 20:49:19 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect
21.03.2012. 20:49:19 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
21.03.2012. 20:49:21 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect
21.03.2012. 20:49:21 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
org.apache.commons.httpclient.ProtocolException: The server xxxxx failed to respond with a valid HTTP response
    at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1846)
    at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1590)
    at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:995)
    at org.apache.commons.httpclient.ConnectMethod.execute(ConnectMethod.java:144)
    at org.apache.commons.httpclient.HttpMethodDirector.executeConnect(HttpMethodDirector.java:495)
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:390)
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
    at test.main(test.java:42)

When I remove that line, everything runs fine as expected.

A: Starting from Apache HTTPComponents 4.3.x HttpClientBuilder class sets the proxy defaults from System properties http.proxyHost and http.proxyPort or else you can override them using setProxy method.

A: Although this question is very old, but I see still there are no exact answer. I will try to answer the question here.
I believe the question in short here is how to set the proxy settings for the Apache commons HttpClient (org.apache.commons.httpclient.HttpClient).
Code snippet below should work :
HttpClient client = new HttpClient();
HostConfiguration hostConfiguration = client.getHostConfiguration();
hostConfiguration.setProxy("localhost", 8080);
client.setHostConfiguration(hostConfiguration);

A: For httpclient 4.1.x you can set the proxy like this (taken from this example):
    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpHost target = new HttpHost("issues.apache.org", 443, "https");
        HttpGet req = new HttpGet("/");

        System.out.println("executing request to " + target + " via " + proxy);
        HttpResponse rsp = httpclient.execute(target, req);
        ...
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

A: Here is how I solved this problem for the old (< 4.3) HttpClient (which I cannot upgrade), using the answer of Santosh Singh (who I gave a +1):
HttpClient httpclient = new HttpClient();
if (System.getProperty("http.proxyHost") != null) {
  try {
    HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
    hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
    httpclient.setHostConfiguration(hostConfiguration);
    this.getLogger().warn("USING PROXY: "+httpclient.getHostConfiguration().getProxyHost());
  } catch (Exception e) {
    throw new ProcessingException("Cannot set proxy!", e);
  }
}

A: Here is how to do that with the last version of HTTPClient (4.3.4)
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost("localhost", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet("/");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

A: I had a similar problem with HttpClient version 4.
I couldn't connect to the server because of a SOCKS proxy error and I fixed it using the below configuration:
client.getParams().setParameter("socksProxyHost",proxyHost);
client.getParams().setParameter("socksProxyPort",proxyPort);

A: If your software uses a ProxySelector (for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector for your HttpClient like this:
ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();

And then do your requests as usual:
HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);


text:
Q: Do we use 'with' or 'to' with 'proportionally'?
The temperature increases proportionally to/with pressure

I found some forums that used 'to' instead of 'with'. I have heard the adjective 'proportional' used with 'to', as 'X is proportional to Y'.
But when it comes to the adverb, I feel 'with' sounds better. But Google search (even though both expressions yield thousands of results, 'to' is more commonly used than 'with') and Ngrams disagrees with me. Any help?

A: OED has, for the phrase in proportion:

in (also †for, †of, †with) proportion: in a known or specific proportion to something else, or as something else varies; proportionately.

The inference is that the phrase in proportion takes the preposition to. This usage is supported by numerous examples, e.g.:

1990   Taxation & Environmental Policy (Inst. Fiscal Stud.) Comm. No. 19. 2   Taxing those who damage the environment in proportion to the damage they do.

The OED has, for the adjective proportional:

3. Math. That is in proportion; (of two or more pairs of quantities) having the same ratio.

Numerous supporting examples indicate that the adjective takes the preposition to, e.g:

1991   C. A. Ronan Nat. Hist. Universe 18/1 (caption)    In Euclidean space, a circle's area is proportional to the square of its radius.

It would be expected that an adverb whose root adjective takes the preposition to would take the same preposition; yet the OED also has, for the adverb proportionally:

a. In a proportional manner or degree; in (due) proportion; correspondingly.

This usage is supported by numerous examples in which the adverb takes the preposition with, e.g.:

1960   A. H. Benade Horns, Strings, & Harmony vi. 110   The frequency of a string rises proportionally with the square root of the tension.

We are clearly on our own here, in the vast unfettered realm that is the living language. The OED would seem to have us use with, but there is no definitive statement to that effect. In the cited OED example provided for the adverb, it modifies the verb rise, which agrees in effect with the verb increase in your example. With a slight preference for with, I would choose the preposition that sounds best to me; either to or with will be understood by an English-speaking reader.

A: Both prepositions "to" and "with" work here, although they have a different meaning.
The most common usage of "proportionally to" is within the scope of comparing something of one thing to something of another and means "to a proportionate degree" (Definition in Oxford Dictionary):

*

*Your salary will rise proportionally to your workload. (Compare the rise of salary to the amount of workload)

*Health problems increased proportionally to the number of hours worked. (Compare amount of health problems to the number of hours worked)
The most common usage of "proportionally with" is within the scope of either by means of something or due to the change of something:

*

*Sevoflurane consumption does not decrease proportionally with fresh gas flows reduction. (A change in fresh gas flows reduction doesn't proportionally decrees Sevoflurane consumption)

*Resizing a figure proportionally with handles. (Resizing a figure proportionally by means of handles)

*Does expressive timing in music performance scale proportionally with tempo? (Does the change of tempo proportionally scale the expressive timing in music?)


text:
Q: Standard LiPo battery packs & product liability I'm designing a high-power portable product that I would like to eventually bring to market. I need to use LiPo battery packs in order to achieve sufficient energy density, but I do not think I will have the resources to navigate the regulatory hurdles associated with LiPo safety.
If I was using Alkaline batteries, for example, I would simply require the consumer to BYO batteries, and therefore not be exposed to the liability if those batteries explode in someone's face!
Lithium Polymer batteries seems to be much less standardised. Is it possible to obtain off-the-shelf standardised LiPo battery products that include internal charging and safety circuitry, where the battery manufacturer is the liable party in the event of a dangerous battery malfunction?
I am not asking for a list of recommendations, rather a confirmation that the approach I'm describing is a valid strategy for outsourcing battery risk.
I feel like this is a common concern in real-life Electrical Engineering and circuit design, so hopefully I'm not too far off-topic for this forum.
Thanks


text:
Q: Discrete time steps in Z3 / CVC4 / SMT-LIB I am defining time steps using an Int in SMT-LIB, which forces me to assert things to make sure nothing happens in the negatives:
(declare-sort Pkg) ; A package
(define-sort Time () Int) ; The installation step
; ...
(assert (forall ((t Time) (p Pkg)) (=> (< t 0) (not (installed p t)))))

I saw that in Z3 we can define inductive Nats in the usual style. Would it be good to use the inductive definition of Nat or is there a better way of doing what I am trying to do above?

A: You should really stick to Int, and put in >= 0 constraints appropriately. Z3 knows a lot about Int, has all sorts of proof rules and tricks to deal with it. While you can indeed define an inductive Nat type, you'll lose all the internal machinery for dealing with integers, and due to the recursive definition Z3's decision procedures will be less effective; especially in combination with other theories.
Having said that, it is impossible to know unless you try: There might be some problem domains where the inductive definition might fit better. But just by purely looking at the kind of you're problem dealing with, good old Int seems to be the right choice for you.
Also see this related question: Representing temporal constraints in SMT-LIB which is definitely relevant in your context.


text:
Q: Only file owners should be allowed to see the files they uploaded I've got an SFTP Server setup, and all users are jailed (chroot) to a specific directory (users are only allowed to upload to this single directory).
The requirement is to ensure that only the file owners can see their files; others don't get to see the files, even if they are in the same group.
Any recommendation on how to get this done on Linux or a code to write to get this done will be helpful. I was thinking there may be a configuration on Linux to get this done.
OS: Linux Fedora 5.14.10


text:
Q: How to isolate a variable in any equation The HP 50g graphing calculator has the ISOL function, that takes an equation and a variable, then proceeds to isolate the given variable on this function and return it.
I have a requirement for developing a solution that does exactly that. Does anyone know this algorithm, or can point me to the right direction on where to find this sort of solution?
As it stands I don't even know the math area that deals with that sort of problem.
This Wolfram|Alpha widget does exactly that: http://www.wolframalpha.com/widgets/view.jsp?id=4acbedbe977480d19b7b682d4878cae2
Any help is greatly appreciated.
Example:
Isolating a variable using Wolfram|Alpha


text:
Q: Calculate time difference according to dd-mm-yy hh:mm:ss in react native Example if the clockin is 3 days ago from today then time will be 72:56:59 something like this right?
So how to calculate using moment? I want result in hh:mm:ss
    const actualTime = new Date("2023-02-23T10:50:51.755Z")
    const currenTime = new Date("2023-02-28T12:50:52.755Z")

    var diff = moment.duration(moment(currenTime).diff(actualTime))
    var diffFormated = moment.utc(diff.as('milliseconds')).format('HH:mm:ss')
    console.log('duration: ', diffFormated);

I try to use this but I got result as wrong time it shows hh:mm:ss according to yesterday but actual result count 23 date to 28 total hour approximately 120 hour...
How to fix it I try to solved last two days but not get exactly time


text:
Q: How to get an access to a view and test if view is visible? I got fragment and got if/else condition. Based on this condition textView visibility VISIBLE / GONE.
How in robolectric test mock or get an access to that textView and check the visibility ?

A: Robolectric is used as an alternative to launch the app in the emulator, you'll want to use espresso to test what state the view is in.
@RunWith(RobolectricTestRunner::class)
class MyUnitTest {

    @Before
    fun setup() {
        // Launch activity or fragment
    }

    @Test
    fun 'view is visble'() {
        // when viewmodel is visible

        // then, Espresso
        onView(withId(R.id.MyViewId))
            .check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
    }

    @Test
    fun 'view is gone'() {
        // then, Espresso
        onView(withId(R.id.MyViewId))
            .check(matches(withEffectiveVisibility(Visibility.GONE)))
    }
}

https://android.github.io/android-test/downloads/espresso-cheat-sheet-2.1.0.pdf


text:
Q: OpenGL Linux poor performance nVidia I'm developing an openGL game for a school project and I'm having performance issues. I'm on Ubuntu, using eclipse indigo 8.0.2 with a makefile project.
My PC is a laptop with double GPU (integrated Intel and dedicated nVidia), so I had the doubt that the GPU used was the integrated one and not the dedicated one.
I tested the graphics with glxgears. The result was 60fps presumably capped. I then used glxinfo to find out the renderer device and found out that the integrated card was being used indeed.
After some research, I found out that with the latest nVidia drivers nvidia prime was released (the new double GPU management). So I succesfully installed the last drivers with nvidia prime.
After this, i tried again glxgears and now i got values around 10000fps, and also glxinfo showed that the dedicated GPU was being used.
I also checked the GPU utilization while running glxgears to triple check that, and the utilization was on 100%. This confirmed what glxinfo showed me.
Now, the problem is, when I executed my openGL game after installing the new drivers I got no preformance improvement.
I checked the GPU utilization while running my game and it was about 20%.
How is that possible that glxgears uses 100% of GPU (and runs at 10000fps instead of 60fps) while my game stays under 20% and runs at ~20fps as it was running on the integrated GPU?
I think 20fps are too few considering my GPU (nvidia gt555m) is able to run games way more complex than my project game (it's just a racing simulator with a motorcycle and few other objects, like some trees, the track, low res environment around) at even 40+ fps.
I hope I explained my problem and someone has any idea about. Thank you.

A:
How is that possible that glxgears uses 100% of GPU (and runs at 10000fps instead of 60fps) while my game stays under 20% and runs at ~20fps as it was running on the integrated GPU?

Your game is CPU bound. Time to profile your code.


text:
Q: Is there any benefit to use wp_localize_script to pass php value to js for ajax call in wordpress? Codex says we need to use wp_localize_script to pass php value to external js file, like the code below:
function bangla_load_scripts($hook){

    global $add_settings;
    if ($hook =! $add_settings) {
        return;
    }

wp_enqueue_script('bangla-ajax', plugin_dir_url(__FILE__).'js/bangla-ajax.js', array('jquery')  );
wp_localize_script( 'bangla-ajax', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 );

}
add_action('admin_enqueue_scripts', 'bangla_load_scripts');

and the file js/bangla-ajax.js is as below:
jQuery(document).ready(function($){
  $('#bangla-ajax-form').click(function(){
    data = {
      'action' : 'bangla_get_results',
      'val1'   : ajax_object.we_value
    }
    $.post(ajax_object.ajax_url, data, function(response){
         alert(response);
    });
    return false;
  });
});

But can't we just simply use 'val1' : $('#selectorid').val()
so that we don't need to use wp_localize_script and all these extra codes, associated with it?

A: If you read the documentation it outlines that you might want to use this method if you are internationalizing your code and require JS variables from PHP that may need to be translated.
From what I gather, besides internationalization it is also a method of keeping your PHP and JS code slightly more seperated than having a mess of PHP variable injections in the middle of your JS code.
As far as your example goes, it's somewhat hard to follow as you don't outline your use-case at all, but from what I gather, if you are just pulling data out of a form element to post it to your ajax endpoint then wp_localize_script isn't even relevant to what you are doing.


text:
Q: Altering a column and cancelling the alter greatly improves SQL performance We have a table that has roughly 5.5 million rows. We use Entity Framework and run a query on this table and get our row of interest based on 2 columns. One FK column that has an index (Type) and another column (ObjectId) that is of type NVARCHAR(MAX) that cannot have an index.
We experienced timeouts in our system. As a proof of concept I was going to change the ObjectId column to a fixed length so I could add an index.
I execute an alter statement . . .
ALTER TABLE Audit.Changes
    ALTER COLUMN ObjectId VARCHAR(50) NULL

After 2 seconds or 2 minutes, I cancel the statement, it has NOT fully executed.
I re-run my test and the query starts to run without any timeout issue.
NOTE: I have tried to run UPDATE STATISTICS without an improvement.
NOTE: If I restore a backup, problem comes back, and I can consistently fix it by running the alter and cancelling it.
My question: what is SQL Server invalidating under the hood or what is it doing where triggering a change on the column or cancelling an alteration to the table would cause the timeout to go away? Is there a direct command I can use to instead of running the statement and a cancel.

A: I'd guess it has read a bunch of pages into the buffer pool and is now running with a "hot" cache. Do your cancelled query thing, test performance, then
CHECKPOINT;
DBCC DROPCLEANBUFFERS;

And test again. Fast or slow?