text:
Q: Troubles of making Django Models work on MS-SQL on MS Azure? I want to create a django web on Azure.
I spent all day on trying to connect my model classes to an exist MSSQL database on Azure.
It still did not work. My hand is tried.
I list my steps, and hope someone to help me thanks a lot!
Step1. Install dependency libraries
sudo pip install --upgrade pip
sudo pip install django-pyodbc
sudo pip install django-sqlserver
sudo pip install django-mssql
sudo pip install django-pyodbc-azure
brew install freetds
brew install freetds --with-unixodbc

Step2. Configuration writing
~/.bash_profile
    #ODBC
    export ODBCSYSINI=/usr/local/opt/unixodbc/etc
    export ODBCINI=/usr/local/opt/unixodbc/etc/odbc.ini

/etc/odbcinst.ini
    [FreeTDS]
    Driver=/usr/local/lib/libtdsodbc.so
    Setup=/usr/local/lib/libtdsodbc.so
    Server={host}
    UsageCount=1
    Port=1433
    Database={db name}
    User={user name}
    Password={password}
    TDS_Version=7.2
    client_charset=utf-8

/etc/odbc.ini
    [FreeTDS]
    Driver = FreeTDS
    ServerName = {hostname}
    Database = {db name}
    UserName = {user name}
    Password = {password}
    Port = 1433
    Protocol = 7.2
    TDS_Version = 8.0

Step3. Try to connect DB.
tsql -S FreeTDS -p 1433 -U {user name} -P {password}

It's ok to connect to 'INFORMATION_SCHEMA' DB。

But when I try:

    tsql -S FreeTDS -p 1433 -U {user name} -P {password} -D {database name}

I had problems:

    Msg 4075 (severity 16, state 1) from {hostname} Line 1:
        "The USE database statement failed because the database collation Chinese_Traditional_Stroke_Order_100_CS_AS_WS is not recognized by older client drivers. Try upgrading the client operating system or applying a service update to the database client software, or use a different collation. See SQL Server Books Online for more information on changing collations."
    Msg 18456 (severity 14, state 1) from {hostname} Line 1:
        "Login failed for user '{user name}'."
    Error 20002 (severity 9):
        Adaptive Server connection failed
    There was a problem connecting to the server

If I try "tsql -S FreeTDS -p 1433 -U {user name} -P {password}" and under,

1> USE somedb
2> go
    Msg 40508 (severity 16, state 1) from {hostname} Line 1:
        "USE statement is not supported to switch between databases. Use a new connection to connect to a different database."

problems again. (I found some pages to says: USE is not work at a MSSQL DB on Azure)

Step4. Try: python manage.py inspectdb > models.py
django.db.utils.Error: ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')

Step5. Try models
settings.py
    DATABASES = {
        'default': {
            'ENGINE': 'sql_server.pyodbc',
            'NAME': '{database name}',
            'USER': '{user name}',
            'PASSWORD': '{password}',
            'HOST': '{hostname}',
            'PORT': '1433',
            'OPTIONS': {
                'driver': 'FreeTDS',
            },
        }
    }

and

$python manage.py shell

>>> from app.models import {ModelName}
>>> {ModelName}.objects.all()

    Error: ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')

(again, no surprise.)

Environments:

*

*Python: 2.7.10

*Django: 1.9.4 (final)

*MS-SQL Server Version: V12

*OS: Mac OSX 10.11.3

*FreeTDS: 0.95.80

*Others
pyobjc-core (2.5.1)
pyobjc-framework-Accounts (2.5.1)
pyobjc-framework-AddressBook (2.5.1)
pyobjc-framework-AppleScriptKit (2.5.1)
pyobjc-framework-AppleScriptObjC (2.5.1)
pyobjc-framework-Automator (2.5.1)
pyobjc-framework-CFNetwork (2.5.1)
pyobjc-framework-Cocoa (2.5.1)
pyobjc-framework-Collaboration (2.5.1)
pyobjc-framework-CoreData (2.5.1)
pyobjc-framework-CoreLocation (2.5.1)
pyobjc-framework-CoreText (2.5.1)
pyobjc-framework-DictionaryServices (2.5.1)
pyobjc-framework-EventKit (2.5.1)
pyobjc-framework-ExceptionHandling (2.5.1)
pyobjc-framework-FSEvents (2.5.1)
pyobjc-framework-InputMethodKit (2.5.1)
pyobjc-framework-InstallerPlugins (2.5.1)
pyobjc-framework-InstantMessage (2.5.1)
pyobjc-framework-LatentSemanticMapping (2.5.1)
pyobjc-framework-LaunchServices (2.5.1)
pyobjc-framework-Message (2.5.1)
pyobjc-framework-OpenDirectory (2.5.1)
pyobjc-framework-PreferencePanes (2.5.1)
pyobjc-framework-PubSub (2.5.1)
pyobjc-framework-QTKit (2.5.1)
pyobjc-framework-Quartz (2.5.1)
pyobjc-framework-ScreenSaver (2.5.1)
pyobjc-framework-ScriptingBridge (2.5.1)
pyobjc-framework-SearchKit (2.5.1)
pyobjc-framework-ServiceManagement (2.5.1)
pyobjc-framework-Social (2.5.1)
pyobjc-framework-SyncServices (2.5.1)
pyobjc-framework-SystemConfiguration (2.5.1)
pyobjc-framework-WebKit (2.5.1)
pyodbc (3.0.10)
django-mssql (1.6.2)
django-pyodbc-azure (1.9.3.0)
django-sqlserver (1.7)

A: Per my experience, it seems that you need to configure the Driver /usr/local/lib/libtdsodbc.so of FreeTDS in the odbc.ini file on your Mac OS.
There is a similiar answered thread you can refer to that suggest to use pymssql package to connect Azure SQL Database. Also, you can see the Azure offical doc Connect to SQL Database by using Python on Ubuntu Linux.

A: I had the same "adaptive server" error.
I solved with the option "host_is_server" in the "OPTIONS" section of the django db configuration:
DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'db',
        'USER': 'user',
        'PASSWORD': 'xxxxxx',
        'HOST': 'host',
        'PORT': '1433',

        'OPTIONS': {
            'driver': 'FreeTDS',
            'host_is_server': True,
        },
    }
}


text:
Q: Moving a DIV using only CSS I need to move a DIV element to the bottom of the body but I can't modify the HTML structure. I thought some existing thread could help me as they explain exactly what I'm looking for but it doesn't seem to be working in my case : Moving a div from bottom to top, using only css. I might be missing something.
Here's my page : https://www.tr-architecte.fr/page-220-auriples-drome

...

...

...

The concerned element is DIV.txt. I want it to be placed right after the div.gallery but can't do it manually as the photos gallery generates itself automatically at the bottom. I can modify classes and styles though.
Let me know if you need more infos.

A: Flexbox can do that:

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

.container-fluid * {
  order: 1;
}

.txt {
  order: 2;
}

1. Row

2. Text

3. Gallery

A: If you cannot change the html structure it's rought, I would have a solution.
Not the best, I don't recommend it, but here it goes:
position: absolute;

This goes on the div with the class .row that contains your text. After the position absolute you have to use bottom: - something px and left: something px. Then you go to your div with the id: social and generate some padding-top: something px.
What I used to test it was :
This on .row
position: absolute;
left: 450px;
bottom: -535px;

This on #social
padding-top: 200px;

As I said, it's a bad practice and I don't recommend it, but since you don't have access to the html, it's your choice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: About complex.h for VS 2013 for window I am compiling a project on VS 2013 and I have introduced the header file #include<complex.h>.
The project involves defining "typedef double _Complex cplx"; when I compile it, I get the following error.
Identifier number "cplx" is not defined
Syntax error: missing ";" (in front of identifier cplx)


text:
Q: How can I see if a timestamp is before now or empty? I'm trying to see if a timestamp is expired. Which it would be, if it's before now or empty.
exp=1662023095
NOW=$(date +%s)
if [[ -z $exp || (($exp < $NOW)) ]]; then
  echo "Update token..."
else
  echo "Token still valid!"
fi

The always echo "Update token...". Can someone tell me what I'm doing wrong?

A: found in the man bash:
When used with [[, the < and > operators sort lexicographically using the current locale.

Give this a try (edited following the @user1934428 comment below)
if [[ -z $exp ]] || (( exp < NOW )) ; then
...

A: The ((...)) doesn't make sense inside [[...]], but you can make it still simpler: If you write it without using $, i.e. as
if (( exp < NOW ))
then
  ...
fi

you don't need to test for an empty exp anymore, because exp would then be interpreted as if it were zero.

A: You are setting the exp to old time:
exp=1662023095
which is always less than the current time
date "+%s"

Sample script:
cat "./73566778.sh"
#!/bin/bash
let exp=1662023095
echo "exp:      $(echo "scale=5;$exp / ( 60 * 60 * 24 * 365)" | bc -q) Years"
let NOW=$(date +%s)
echo "1662023095 seconds is always less than current second $NOW"
echo "NOW:      $(echo "scale=5;$NOW / ( 60 * 60 * 24 * 365)" | bc -q) Years"
echo "if [[ -z $exp ||  $exp -lt  $NOW ]]"
if [[ -z $exp ||  $exp -lt  $NOW ]]
then
        echo "Update token..."
else
        echo "Token still valid!"
fi

Output:
$ ./73566778.sh
exp:    52.70240 Years
1662023095 seconds is always less than current second 1662025519
NOW:    52.70248 Years
if [[ -z 1662023095 ||  1662023095 -lt  1662025519 ]]
Update token...

Hence this will always display:
Update token...
Based on your comment:

I'm trying to see if a timestamp is expired.
You have to write other script which is having exp data
exp=...
to update current script.


text:
Q: Sustainable text in input field I have input text field and I have a placeholder inside. When I click on input, placeholder disappears. I am using jQuery Watermark plugin for this placeholders. I want to change this behavior. I need that placeholder to stay in input when user types in this field.
Nice example would be field for e-mail. In one step, user gives me domain name, for example 'foo.com'. Placeholder for e-mail will look like '@foo.com'. When user clicks on this field, I want this placeholder to act like value of that input, but unchangeable. Default value of my e-mail input field is '@foo.com', when user types in 'bar' its 'bar@foo.com'.
I hope you understand what I am trying to do :) How can I achieve this behavior?

A: You can just have a absolutely positioned label for this. Also, you could handle onclick and onblur events on the input in case you want to hide the label. Try this:

        <form>

                @foo.com
                <input type="text" value="" name="email" style="border:1px solid #939393; line-height:28px;text-align:left;font-size:14px;padding-left:5px;color:#000;z-index:1;width:300px;height:30px" />

        </form>

A: You can use this function. I have used it once in my code (with help from stackoverflow) :
html:
<input type="text" id="t1" placeholder="@foo.com">

javascript:
function setRange(input, textStart, textEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(textStart, textEnd);
    }
else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', textEnd);
        range.moveStart('character', textStart);
        range.select();
    }
}
function setCursorPos (input, pos) {
    setRange(input, pos, pos);
}

$("#t1").click(function() {
    $(this).val("@foo.com");
    setCursorPos(document.getElementById("email"), 0);
});


text:
Q: logback-spring.xml does not work when deploy on tomcat I hava create spring boot project with Java 8, and I am using external Tomcat container to deploy. I hava a logbakc-spring.xml as follows:
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>INFO</level>
    </filter>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/log/hfxn.%d{yyyy-MM-dd}.log</fileNamePattern>
    <maxHistory>90</maxHistory>
    </rollingPolicy>
    <encoder>
        <charset>utf-8</charset>
        <Pattern>%d %-5level [%thread] %logger{0}: %msg%n</Pattern>
    </encoder>
</appender>

But, when I build into war, and deploy on Tomcat, I cannot find the log file in the path where I specified, and , I don't know why?

A: A logback file named logback-spring.xml works well if your project is spring-boot compatible, but when you deploy your project as war into tomcat, this file is not picked because of naming a constraint on logback file.
A logback file can have only 1 of these 3 allowed names:

*

*logback-test.xml

*logback.groovy

*logback.xml
As soon as you change the name of the file as one of the above, logback config will start working with war package deployed over Tomcat.

A: Do you see the logback file found in the console messages?  Try naming the file logback.xml, which is a standard logback name that it searches for at startup.  Also, ensure the file is at the top level in the jar, not nested in a subdirectory.


text:
Q: Prolog planner only generates one plan I have a prolog planner which works correctly with one major problem of only generating one plan at the time. The plan is correct but for my application I really need to have all the possible plans.
plan(State, Goal, _, Moves) :-  subsetB(Goal,State),
                            write('moves are'), nl,
                            reverse_print_stack(Moves).
plan(State, Goal, Been_list, Moves) :-
                            effects(Name, [Preconditions, Add,Delete]),  //a list of of rules governing the domain
                            conditions_met(Preconditions, State),       //checks if all preconditions are present in the state
                            change_state(State, Add,Delete, Child_state), //add predicates from Add list, removes predicates in the Delete list and stores result in Child_state
                            \+(member_state(Child_state, Been_list)),     //checks if Child_state hasn't been previously visited
                            stack(Child_state, Been_list, New_been_list),
                            stack(Name, Moves, New_moves),
                    plan(Child_state, Goal, New_been_list, New_moves).

change_state(S, [],[], S).
change_state(S, [], Delete, S_new) :-   change_state(S, [],[], S2),
                                    apply_del(Delete, S2, S_new).
change_state(S, Add,Delete, S_new) :-   change_state(S, [], Delete, S2),
                                    apply_add(Add, S2, S_new).

apply_add([],State,State).
apply_add([activate(App)|Rest],State,InterimState) :-apply_add(Rest,State,S2),find_stones(App,State,StonesToBeActivated), make_active(StonesToBeActivated,S2, InterimState).
apply_add([First|Rest],State,InterimState) :- apply_add(Rest,State,S2),add_element(First, S2, InterimState).

apply_del([],InterimState,InterimState).
apply_del([First|Rest],InterimState,NewState) :- apply_del(Rest, InterimState,S2),del_element(First, S2, NewState).

subsetB([],_).
subsetB([F|R],S) :- member(F,S),subsetB(R,S).

%dropping a stone inside app1
 effects(drop(X,app1),                     %action
   [[stone(X),active(X)],                  %preconditions
    [in(app1,X)],                          %postconditions : add list
    [active(X)]]).                         %postconditions : delete list

go(S,G,AllPlans):- findall(Moves, plan(S,G,[S],Moves),AllMoves).

conditions_met(P, S) :- subsetB(P, S).

Sample call
   go([in(app1,s1), stone(s2), active(s2),stone(s3),active(s3)],[in(app1,s1),in(app1,s3),in(app1,s2)],AllPlans).
Answer:
drop(s2,app1)
drop(s3,app1)        //correct
_2368
_2366
_2364
_2362
_2360
_2358
_2356
_2354
_2352
_2350
_2348
_2346
_2344
_2342
_2340
_2338
_2336
etc... infinitely

A: For finding all solutions to a goal, look at bagof or findall. Or am I missing something?
Like this:
?- findall(Moves, plan(State, Goal, _, Moves), AllMoves).

The whole idea of these predicates is that you say which arguments you want to collect and get a list of all possible instantiations under that predicate. In this sense you normally have a "return" value (an argument that gets instantiated with the result) that you can then look at or print, instead of printing it explicitly in the predicate that finds solutions.
A simplistic example:
foo(1). foo(2). foo(3). foo(4). foo(5). foo(6).
bar(R) :- foo(A), A mod 2 =:= 0.

findall(R, bar(R), Even).

Now to recursion: how does it work? You cannot share variables between different clauses of the same predicate. For example, this is wrong:
baz(0, B).
baz(X, B) :- X0 is X - 1, B1 is B + 1, baz(X0, B1).

because B is a singleton variable in the first clause of baz. Instead, you can do:
baz(0, B, B).
baz(X, B, Result) :- X0 is X - 1, B1 is B + 1, baz(X0, B1, Result).

which you can now call:
?- baz(10, 2, Result).
Result = 12

but you will still run into problems after the first answer.
You get the single correct plan probably because the first clause of plan does not meet the requirements of subsetB, and you get to the second clause. There, you make a Moves that has a free variable at its Tail, but this is not a problem yet. The problem is, however, that when you find your first solution (all in the second plan clause, recursively), Moves is now bound to a list of actions, and instead of starting to look for a new solution, you get into the second clause again by backtracking, with the already filled in Moves, which probably messes up the rest of the algorithm.
To make it correct, you probably need to make sure that when your plan backtracks, it starts to look for a new solution, with a clean Moves. You can start by instantiating Moves to an empty list and collecting results in an accumulator, as shown in the simplistic baz predicate above.


text:
Q: Picasso - Custom RequestHandler doesn't cache images on disk I need to load and cache images from some service. In example there is no such a service but it shows what I want to achieve.
My problem is that images aren't cached on disk. There is no usual folder /data/data/myapp/cache/picasso-cache.
How can I access cache from RequestHandler. It is even possible or it will be better to write custom Downloader?
RequestHandler
public class CustomRequestHandler extends RequestHandler {

    private static final List<String> PATHS = Arrays.asList("http://somelink/someimage1.png",
            "http://somelink/someimage2.png",
            "http://somelink/someimage3.png");

    private Iterator<String> pathIterator = PATHS.iterator();

    @Override
    public boolean canHandleRequest(Request data) {
        return data.uri.toString().contains("custom");
    }

    @Override
    public Result load(Request request, int networkPolicy) throws IOException {
        if (!pathIterator.hasNext()) {
            pathIterator = PATHS.iterator();
        }

        Bitmap bitmap = downloadFullFromUrl(pathIterator.next());
        Result result = new Result(bitmap, Picasso.LoadedFrom.NETWORK);
        return result;
    }

    private static Bitmap downloadFullFromUrl(String imageFullURL) {
        Bitmap bm = null;
        try {
            URL url = new URL(imageFullURL);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0,
                    baf.toByteArray().length);
        } catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
        return bm;
    }
}

Usage:
Picasso picasso = Picasso.Builder(application)
                .addRequestHandler(requestHandler)
                .build();

picasso.load("custom").into(imageView);

A: As @sashabelonogov mentioned, you need to have your picasso instance with the request handler as a singeltone instance. I did it just by adding this to my Application class and use Picasso.with(Context) everywhere.
public class MyApplication extends Application {

    public void onCreate() {
        super.onCreate();
        Picasso picasso = new Picasso.Builder(getApplicationContext())
                .addRequestHandler(new MyRequestHandler())
                .build();
        Picasso.setSingletonInstance(picasso);
    }
}

A: You should not declare a few instances of Picasso. If you want to use a custom Picasso instance, make it as a Singleton. It worked for me. Good luck!
Another advice:
It might be more comfortable to use Downloader class (OkHttpDownloader.java or some other one) instead of downloadFullFromUrl() method.


text:
Q: Understand a type as another Suppose I have a class A and a class B.
class A {
    public void foo1(){ print("foo1"); }
    public void foo2(){ print("foo2"); }

    ...
    public void fooN(){ print("fooN"); }
}

class B {
    public A a;
}

When I call B, I'd like it to behave as if it was an instance of A, so I could do this:
B b = new B();
B.a = new A();
B.foo1();

How can I achieve this behaviour? I tried to add this function in B but it didn't work:
public static implicit operator A(B instance) { return instance.a; }

PS: A cannot be inherited from.

A: If you want to call B.foo1() change class B to :
class B
{
    public void foo1() {
      if(a!=null) a.foo1();
    }
    .........
    .........
    public A a {get; set;}
}

Any other way you will not be able to compile your code. b.foo1() will give a compiler error. You can use reflection and call something like b.aMethod("foo1") but it is a different story.


text:
Q: Change Entity framework database schema at runtime In most asp.net applications you can change the database store by modifing the connectionstring at runtime.  i.e I can change from using a test database to a production database  by simply changing the value of the "database" field in  the connectionstring
I'm trying to change the schema (but not necessarily the database itself) with entity framework but no luck.
The problem I'm seeing is the that the SSDL content in the edmx xml file is storing the schema for each entityset.
see below
<EntitySet
    Name="task"
    EntityType="hardModel.Store.task"
    store:Type="Tables"
    Schema="test"  />

Now I have changed the schema attribute value to "prod" from test and it works..
But this does not seem to be a good solution.

*

*I need to update evert entity set as well as stored procedures ( I have +50 tables )

*I can only do this an compile time?

*If I then try to later update the Entity model-entityies that already exist are being read due to EF not recognizing that the table already exists in the edm.

Any thoughts?

A: I have this same issue and it's really rather annoying, because it's one of those cases where Microsoft really missed the boat. Half the reason to use EF is support for additional databases, but unless you go code first which doesn't really address the problem.
In MS SQL changing the schema makes very little sense, because the schema is part of the identity of the tables. For other types of databases, the schema is very much not part of the identity of the database and only determines the location of the database. Connect to Oracle and changing the database and changing the schema are essentially synonymous.

A: The easiest way to solve the problem is to manualy remove all entries like 'Schema="SchemaName"' from the SSDL part of the model.
Everything works propely in this case.

A: Update Upon reading your comments it's clear that you're wanting to change the referenced schema for each DB, not the database. I've edited the question to clarify this and to restore the sample EDMX you provided which was hidden in the original formatting.
I'll repeat my comment below here:

If the schemata are in the same DB, you can't switch these at runtime (except with EF 4 code-only). This is because two identically-named and structured tables in two different schemata are considered entirely different tables.

I also agree with JMarsch above: I'd reconsider the design of putting test and production data (or, actually, 'anything and production data') in the same DB. Seems like an invitation to disaster.
Old answer below.
Are you sure you're changing the correct connection string? The connection string used by the EF is embedded inside the connection string which specifies the location of CSDL/SSDL/etc. It's common to have a "normal" connection string for use by some other part of your app (e.g., ASP.NET membership). In this case, when changing DBs you must update both of your connection strings.
Similarly, if you update the connection string at runtime then you must use specific tools for this, which understand the EF connection string format and are separate from the usual connection string builder. See the example in the link. See also this help on assigning EF connection strings.

A: Sorry its not a robust answer but I found this project on codeplex ( as well as this question ) while googling around for a similar problem:
http://efmodeladapter.codeplex.com/
The features include:

*

*Run-time adjustment of model schema,
including:

*Adjusting data-level table
prefixes or suffixes

*Adjusting the
owner of database objects

Some code from the docs:
public partial class MyObjectContext : BrandonHaynes.ModelAdapter.EntityFramework.AdaptingObjectContext
{
        public MyObjectContext()
        : base(myConnectionString,
        new ConnectionAdapter(
            new TablePrefixModelAdapter("Prefix",
                new TableSuffixModelAdapter("Suffix")),
        System.Reflection.Assembly.GetCallingAssembly()))
    {
    ...
    }

}
Looks like its exactly what your looking for.

A: The connection string for EF is in the config file. There is no need to change the SSDL file.
EDIT
Do you have the prod and test schema in the same database?
If Yes you can fix it by using a seperate database for prod and test. Using the same schema name in both databases.
If No you can fix it by Using the same schema name in both databases.
If you will absolutly have different schema names, create two EF models, one for test and one for prod, then select which on to use in code based on a value in your config file.

A: When I create a new "ADO.NET Entity Data Model", there are two properties "Entity Container Name" and "Namespace" available for editing in design view..  Using the namespace.EntityContainerName, you can create a new instance specifying a connection string.
MyEntities e = new MyEntities("connstr");
e.MyTable.Count();
I'm not sure if this helps you or not, good luck!
Also, this is a good case for multiple layers (doesn't have to be projects, but could be).
Solution
 * DataAccess - Entities here
 * Service - Wraps access to DataAccess
 * Consumer - Calls Service
In this scenario, the consumer calls service, passing in whatever factor determines which connection string is used.  The service then instantiates an instance of data access passing in the appropriate connection string and executes the consumer's query.

A: Here is a similar question with a better answer:
Changing schema name on runtime - Entity Framework
The solution that worked for me was the one written by Jan Matousek.

A: Solved my problem by moving to sql server and away from mysql.
Mysql and Mssql interpret "schemas" differently. Schemas in mysql are the same/synonyms to databases. When I created the model the schema name..which is the same as the database name is hard coded in the generated model xml. In Mssql the schema is by default "dbo" which gets hard coded but this isnt an issue since in mssql schemas and databases are different.


text:
Q: Wordpress swapping div content with php do_shortcode I have a script with in my wordpress header. I want to dynamically load a form into a container with clicking a button. There are two forms total, and of course one button per form.
When I store the do_shortcode function into a php variable, store the php variable into a jquery variable, the shortcode executes. When i change the html value of the container with the variable echoing the php do_shortcode variable, it does NOT render the form, but only the shortcode value. What am I doing wrong?
<?php $cf7Shortcode = do_shortcode( "[contact-form-7 id='11' title='form']" ); ?>

<script type="text/javascript">
$(document).ready(function() {

    var form1 = <?php echo $cf7Shortcode ?>,
        form2 ='test',

        button1 = $('#btn1'),
        button2 = $('#btn2')

        formContainer = $('#form-container');

    button1.on("click", function(){
        formContainer.html(form1);
    });

    button2.on("click", function(){
        formContainer.html(form2);
    });

});

</script>

A: In your theme's functions.php file, we'll want to declare the ajax function we wish to run.
add_action('wp_ajax_get_contact_form', 'get_contact_form');
add_action('wp_admin_ajax_get_contact_form', 'get_contact_form');

This will register your ajax hook for the function get_contact_form
function get_contact_form(){
    if(isset($_GET['form_id'])):
        echo do_shortcode( "[contact-form-7 id='$_GET['form_id']' title='form']" );
    endif;
    exit(); //need this, or you'll have issues with getting '1' back as a value
}

Now when you make an ajax request with action: get_contact_form, it will attempt to run the above function. Since we aren't passing parameters into the function, we're going to check if form_id was set, if it was, we'll return the shortcode. We have to exit regardless.
Let's set up our ajax call.
buttons.click(function(){
    $.ajax({
        url: ajaxurl, //global variable provided by WP
        type: 'GET',
        data: {
            'action' : 'get_contact_form',
            'form_id' : $(this).data('form')
        },
        success: function(data){
            formContainer.html(data);
        }
    });
});

The key pieces above are $(this).data('form'), which is a data attribute. It looks like you have control of the markup, so add reference to the ID of the form you want to get to your HTML, like this ->
data-form="11"

The second key piece is success:function(data){, when the ajax request is successful, it will take the data returned and make it the HTML of the formContainer. In our case, it will be the form.
Finally, instead of using id's, use a class for your buttons.
class="ajax-form-button"

Then instead of var button1 = / button 2 =, just do buttons = $('.ajax-form-button'). Then we don't have to make a bunch of click/ajax functions, because we're allowing the logic to be handled by the data-form attribute. This will keep the code minimal and reusable.
I don't think I've forgotten anything here.


text:
Q: Prove that $f'(a) = \frac{1}{2\pi}\int_0^{2\pi}e^{-i\theta}f(a+e^{i\theta})d\theta$ I know this is to be derived from Gauss' Mean Value Theorem, but I can't get the $e^{-i\theta}$. Where am I going wrong?
$f'(a) = \lim_{h \to 0}\frac{f(a+h) - f(a)}{h} = \lim_{h\to 0}\frac{1}{2pi}\int_0^{2\pi} \frac{f(a+e^{i\theta}+h)-f(a+e^{i\theta})}{h}d\theta = \frac{1}{2\pi}\int_0^{2\pi}ie^{i\theta}f'(a+e^{i\theta})d\theta$.
Clearly, this isn't correct, but I don't know where I went wrong.

A: First of all, since $\int_0^{2 \pi} e^{-i \theta} d\theta=0$, we can rewrite the integral as
$$\frac{1}{2\pi} \int_0^{2 \pi} e^{-i \theta}(f(a+e^{i \theta})-f(a)) d \theta= \frac{1}{2 \pi} \int_0^{2 \pi} \frac{f(a+e^{i \theta})-f(a)}{a+e^{i \theta}-a} $$
Thus you are taking the mean value of the (analytic) function $$\frac{f(z)-f(a)}{z-a} $$ over the unit circle.
I will also add that this function has a removable singularity at $z=a$, with limiting value $f'(a)$.


text:
Q: Iterate over all machine inner documents I got this JSON and I want to iterate over all inner fields inside machine: machine.id (inner machine objects, one by one and get the id)
{
    "_id" : ObjectId("60b72eb607d158d886626648"),
    "accountId" : "10304",
    "dayKey" : 20210602,
    "twin" : "c9750367-36fe-4e1f-a9bb-54f44c1cd8d8",
    "ttl" : ISODate("2021-06-02T07:09:37.515Z"),
    "machines" : {
        "dff2a2c3-6765-425a-8cb8-26b3f9c6214d-machine-54652" : {

            "ioSize" : [
                14.7014119238827,
                14.1548860858939,
                14.5505302898045,
                15.554507463338,
                14.4255739350559,
                14.5063722067039,
                15.459819090433,
                14.3030780813547,
                14.1884056389665,
                14.4948280377095,
                13.3577492143855, a
                14.7608731232542,
                15.9873265101257,
                13.4887886260475,
                15.7738139402933,
                15.9362888442737,
                14.7705187238128
            ],
            "id" : "dff2a2c3-6765-425a-8cb8-26b3f9c6214d.machine-54652"
        },
        "dff2a2c3-6765-425a-8cb8-26b3f9c6214d-machine-35562" : {

            "ioSize" : [
                37.7397106319832,
                38.9988270338687,
                38.5746933921089,
                38.0871104661313,
                39.2368627793296,
                38.5768210981145,
                40.0075015275838,
                38.4587879713687,
                38.7158966916899,
                38.8449393331006,
                38.9401787273045,
                38.6076837465084,
                39.5514468400838,
                46.7157111993715,
                48.3111469972067,
                38.5859375,
                38.9902398306564
            ],
            "id" : "dff2a2c3-6765-425a-8cb8-26b3f9c6214d.machine-35562"

        }
    }
}


text:
Q: How Should I Think About the Dirac Equation? In Weinberg's QFT Vol. 1 he says the Dirac equation is not a true generalization of Schrodinger's equation, that it does not stand up to inspection when viewed in this light. He says it should be viewed as an approximation to a true relativistic quantum field theory of photons and electrons.

*

*I do not understand what this means, would someone mind filling me
in? (Assuming he's saying something more general & subtle than merely saying Dirac is not a one-particle equation)

One of Dirac's motivations for his derivation was that Klein-Gordon was not first order in time like the non-relativistic Schrodinger equation is.

*

*Since the 2'nd order in time Klein-Gordon equation does actually
describe something physical, does this mean Dirac's point about not
being first-order in time is actually flawed, and that Dirac's equation worked for some other reason?

From browsing Cartan's Spinor's book it seems the Dirac equation holds for any spinor, it apparently relates left & right representations of a spinor or something, thus it holds in GR etc... There is also this great quote from Atiyah that a spinor is a square root of a geometry.

*

*What is the Dirac equation & how does this explain why Dirac's
derivation worked, why it relates representations of a spinor &
explains this square root of a geometry business?

A: 'Square root of geometry'
A Dirac spinor field $\psi^\alpha(x)$ under Lorentz transformations behaves as,
$$\psi^\alpha(x)\to S[\Lambda]^\alpha_\beta \psi^\beta(\Lambda^{-1}x)$$
where $\Lambda = \exp(\frac{1}{2} \Omega_{\rho\sigma}\mathcal{M}^{\rho\sigma})$ and $S[\Lambda] = \exp(\frac{1}{2}\Omega_{\rho\sigma}\mathcal{M}^{\rho\sigma})$, where $\mathcal{M}$ are the generators of the Lorentz transformations; they are anti-symmetric and obey the Lorenz Lie algebra. The matrices $S$ satisfy the spinor representation of the Lorenz group (exercise!), and are defined by,
$$S^{\mu\nu} = \frac{1}{4}[\gamma^\mu,\gamma^\nu]$$
A general rotation matrix acting on a spinor may be written as,
$$\left(
\begin{array}{cc}
e^{i\varphi \cdot \sigma /2} && 0\\
0 && e^{i\varphi \cdot \sigma /2}
\end{array}
\right)$$
A rotation by $2\pi$, i.e. an entire turn, around the $x^3$ axis is given by the choice $\varphi = (0,0,2\pi)$, and the rotation matrix becomes,
$$\left(
\begin{array}{cc}
e^{i\pi  \sigma^3} && 0\\
0 && e^{i\pi  \sigma^3}
\end{array}
\right) = -1$$
Hence, under a full turn, a spinor transforms as, $\psi^\alpha(x) \to -\psi^\alpha(x)$, in other words it does not return to its original state. That's why we call them the 'square root of geometry.' You in fact have to rotate them fully twice rather than once.


text:
Q: How to load object depending on a input$select I'm trying to load a R object in a Shiny app. I have 2 objects, and depending on which option user selected, I need to load one or another.
I can load one object if I call the load object outside shinyServer(function(input, output) {})
But I need load it inside, depending on the user selected option.
My code is like:
shinyServer(function(input, output) {
        observeEvent(input$select,{
                if(input$select==1){
                        DT1<-load(file = 'DT1N', envir=.GlobalEnv)
                }else DT1<-load(file = 'DT1B', envir=.GlobalEnv)
        }
})

Thank you!

A: Instead of observeEvent which doesn't return any value (and is used for side effects), use eventReactive which is about the same but the difference is that it does return a value. You can then access it with DT1().
shinyServer(function(input, output) {
  DT1 <- eventReactive(input$select,{
    if(input$select==1){
      return(load(file = 'DT1N', envir=.GlobalEnv))
    }else return(load(file = 'DT1B', envir=.GlobalEnv))
  }
})


text:
Q: Avalonia UI Carousel Example I'm rather new to Avalonia UI / XAML / .NET MVVM in general. While I really like Avalonia so far, it's still in beta and lacks extensive documentation. Hence I sometimes struggle to get specific things working or finding out how I should use them correctly.
Could somebody point me to an example using the Carousel control? Which properties should I set in the xaml, what kind of item list should be behind it etc?
Cheers.

A: You can find usage example in ControlCatalog project from the main repository:
https://github.com/AvaloniaUI/Avalonia/blob/master/samples/ControlCatalog/Pages/CarouselPage.xaml
https://github.com/AvaloniaUI/Avalonia/blob/master/samples/ControlCatalog/Pages/CarouselPage.xaml.cs


text:
Q: How do you extract lines with two conditions from txt file, a word and a number? I want to get the numbers in valid lines only with Python so
1234, 345.2, 3455 from line 1
7644, 6564.1, 1325 from line 3
89473, 8479, 2434 from line 5
txt file

books|1234|345.2|3455|valid
books|9875|5466.1|invalid
books|7644|6564.1|1325|valid
books|5435|4535.2|invalid
books|89473|8479|2434|valid

A: with open("test.txt",'r') as fil: #open file
    for line in fil.readlines(): #read it line by line
        #remove newline and split into list, elements separated by |
        temp=line.strip().split('|')
        if temp[-1]=="valid": #Check if "valid" is last element
            print(temp[1:-1]) #print all elements between first and last

This is just printing the values, but it should be fairly easy to instead store the values however you want.


text:
Q: Extract feelds as key value from a json object in mariadb Hello I want to extract the different field values of a json object as key value pairs, but I'm not able to do that.
I tried this
SELECT JSON_EXTRACT(chapters, '$[*].Id', '$[*].Name') AS rec
  FROM `Novels`
 WHERE 1

but it result looks like this
["1","first Name","2","second name"]
any idea on how to convert it to something like this
{"1":"first Name","2":"second name"}
Thanks in advance!

A: One option uses json_table() to unnest the array to rows (available in MySQL 8 only) then aggregation:
select
    t.*,
    (
        select json_objectagg('id', x.id, 'name', x.name)
        from json_table(
            t.chapter,
            '$[*]'
            columns (
                id int path '$.Id',
                name varchar(50) path '$.Name'
            )
        ) as x
    ) as obj
from mytable t

A: Depending on the result, the concerned value of the chapters column should be
'[ {"Id":"1","Name":"first name"}, {"Id":"2","Name":"second name"} ]'

JSON_EXTRACT() can be applied for each element of the array in order to determine Id values as keys part, and Name values as values part.
And then, JSON_UNQUOTE() can be applied to get rid of double-quotes while generating rows for each individual array elements. JSON_OBJECTAGG is used to aggregate all those extracted objects at the last step provided that MariaDB version is 10.5+:
WITH n AS
(
SELECT @i := @i + 1 AS rn,
       JSON_UNQUOTE(JSON_EXTRACT(chapters, CONCAT('$[',@i-1,'].Id'))) AS js_id,
       JSON_UNQUOTE(JSON_EXTRACT(chapters, CONCAT('$[',@i-1,'].Name'))) AS js_name
  FROM information_schema.tables
 CROSS JOIN ( SELECT @i := 0, chapters FROM `Novels` ) n
 WHERE @i < JSON_LENGTH(JSON_EXTRACT(chapters, '$[*]'))
)
SELECT JSON_OBJECTAGG(js_id,js_name) AS Result
  FROM n

A Workaround might be given for DB version prior to 10.5 as
SELECT CONCAT('{',
       GROUP_CONCAT(
                    REPLACE(
                            REPLACE( JSON_OBJECT(js_id,js_name) , '}', '')
                            , '{', '')
                    )
        , '}') AS Result
  FROM n

Demo


text:
Q: ASP.NET MVC 2: Avoiding loop when accessing 404 action directly Like many people using ASP.NET MVC, I've implemented my own custom 404 error handling scheme using an approach similar to the one described here: How can I properly handle 404 in ASP.NET MVC?
(I actually discovered that post after implementing my own solution, but what I came up with is virtually identical.)
However, I ran into one issue I'm not sure how to properly handle. Here's what my 404 action in my ErrorController class looks like:
    public ActionResult NotFound(string url)
    {
        url = (url ?? "");

        if (Request.Url.OriginalString.Contains(url) &&
            Request.Url.OriginalString != url)
        {
            url = Request.Url.OriginalString;
        }

        url = new Uri(url).AbsolutePath;

        // Check URL to prevent 'retry loop'
        if (url != "/Error/NotFound")
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;

            // Log 404 error just in case something important really is
            // missing from the web site...
            Elmah.ErrorSignal.FromCurrentContext().Raise(
                new HttpException(Response.StatusCode,
                    String.Format("Resource not found: {0}", url)));
        }

        return View();
    }

The part that's different from the answer in the other StackOverflow question I referenced above is how the 'retry loop' is prevented. In other other answer, the code that prevents the retry loop simply sets properties on a ViewModel, which doesn't seem to actually prevent the loop. Since the action is sending back a response code of 404, then accessing the action directly (by typing "/Error/NotFound" in the browser) causes an infinite loop.
So here's my question: Did I miss another, more obvious way to handle the retry loop issue, or is my approach a decent way to do this?

A: you can handel erros by enabling the customErrors mode in the web.config file and set it to redirect errors to your controller when any errors occurs.
see an example here


text:
Q: Double callbacks onMenuOpened/onPanelClosed on each menu button press In my Android app I want to collect statistics on when (how often) the overflow (three dots) action bar menu is opened and closed (without an item being selected). For this task I have overriden onMenuOpened and onPanelClosed methods within an Activity. However, on all the devices (Android 4.4, 4.2; Samsung and HTC) I've tried  this so far these methods are triggered twice, each time the menu is opened and closed.
Is this a bug? Is there another way to monitor this menu opening and closing?

A: you can try this...i have tested it ....it works perfect....
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    Activity activity = getActivity();
    activity.getActionBar().addOnMenuVisibilityListener(new OnMenuVisibilityListener() {
    @Override
        public void onMenuVisibilityChanged(boolean isVisible) {
            // TODO Auto-generated method stub
            //you can check the isVisible boolean to check
            // if the overFlowMenu is visible or not
        }
    });

A: I got the same question as you, and find an easier way to solve it:
When the first time it enters onMenuOpened(), menu is null. The menu is not prepared yet. So, you can check as below
@Override
public boolean onMenuOpened(int featureId, Menu menu){
    if(menu!=null){
       //log something like firebaseLogEvent("Action", "onMenuOpened");
    }
    return true;

}

A: Discovered a better solution
    public boolean onPrepareOptionsMenu(Menu menu) {
      if (hasWindowFocus ()) {
        // gets called every time user taps on menu
        Log.v(TAG, "onPrepareOptionsMenu - focus");
      } else {
        // gets called when menu is being initialized
        Log.v(TAG, "onPrepareOptionsMenu - NO FOCUS");
      }
      return super.onPrepareOptionsMenu(menu);
    }

You can collect you stats in the "focus" part of the If statement.


text:
Q: DropDownList "has a SelectedValue which is invalid because it does not exist in the list of items" I have a ASP.NET DropDownList, which I data-bind to a list of objects, and then it throws an exception. This error is driving me nuts, because the message is wrong, and the value clearly does exist in the list of items, as shown by the screenshot:

Here's the relevant ASP.NET markup:
<asp:DropDownList ID="_ddlRequests" runat="server" AppendDataBoundItems="true" DataTextField="RequestNumber" DataValueField="RequestNumber">
    <asp:ListItem Text="" Value="" />
</asp:DropDownList>

A: It may be worth first databinding and then adding your blank value. Something along the lines of:
_ddlRequest.Datasource = request;
_ddlRequest.DataBind();
_ddlRequest.Insert(0, new ListItem("", ""));

The only reason I suggest this is that I came across this before and after banging my head in frustration for a while just settled on doing it this way instead.

A: You can use below code to clear data on DropDownList
_ddlRequest.Items.Clear()


text:
Q: No cargan las imagenes en mi pagina web tengo el siguiente problema, en el editor de código cargo mi imagen y se ve genial perfecto
pero cuando entro a la pagina directamente pulsando el archivo index.html no se ven las imagenes
cargadas desde css. solo las que estan directamente en el html se pueden visualizar.
estoy voy chequeo las rutas, el nombre de la imagen que no tenga caracter especial sin espacios ni nada cargo y desde el editor si abro la pagina se visualiza bien.. pero si la abro desde
el index.html haciendo click no puedo visualizar estas imagenes y tengo ese mismo problema
en dos paginas que realize el dia de ayer...
he agotado todos los recursos y no encuentro la manera de resolver esto.


text:
Q: How can I make this query? This is the table for testing
----------------------------------------------
id | username | point | level | created_date
----------------------------------------------
 1 | name_a   |  1    |   1   | 2011-08-01
 2 | name_a   |  2    |   2   | 2011-08-02
 3 | name_b   |  5    |   1   | 2011-08-02
 3 | name_c   |  6    |   1   | 2011-08-02
 4 | name_d   |  1    |   1   | 2011-08-01
 5 | name_d   |  3    |   1   | 2011-08-02
 5 | name_d   |  5    |   2   | 2011-08-03
 4 | name_e   |  5    |   1   | 2011-08-01
 5 | name_e   |  5    |   2   | 2011-08-02
 5 | name_e   |  5    |   3   | 2011-08-03
----------------------------------------------

Requirement for the query is to query (as much as possible in one query) the username, point of the table.

*

*Order by sum of user's score on each level.

*If user have 2 score on the same level, it will only get the latest score.

*Group by username

*total score must be less than 10

*maximum of the score per level is 5

Output sample:
--------------------
 username  | tpoint|
--------------------
  name_d   |  8    |
  name_b   |  5    |
  name_a   |  3    |
--------------------

name_e and name_c was ignored.

A: Sounds like a fun query!
SELECT username, SUM(point) AS points
FROM (SELECT username, level, point
      FROM (SELECT username, level, LEAST(point, 5) AS point
            FROM table
            WHERE points <= 5
            ORDER BY created_date DESC) AS h
      GROUP BY username, level) AS h2
GROUP BY username
HAVING points < 10
ORDER BY points DESC

This should do it! Just replace "table".
EDIT:
Do you want to exclude rows which got a score over 5, or have the value as 5? Just remove WHERE points <= 5 if such.

A: SELECT SUM(t3.point) AS tpoint, t3.username
FROM (
    SELECT t1.level, t1.username, t1.created_date, t1.point
    FROM testing AS t1
    INNER JOIN (SELECT level, username, MAX(created_date) AS MaxDate
                FROM testing) AS t2
          ON (t1.level=t2.level AND t1.username=t2.username AND t1.created_date = t2.MaxDate)
    WHERE t1.point <= 5
    ) AS t3
GROUP BY t3.username
HAVING tpoint < 10
ORDER BY tpoint DESC

Don't know if I used the aliases correctly, hope this works!
The inner query with the join is to get the latest username,level combination where single level point count is > 5. This is then used to get the total sum per username and discard those with more then 10 points.

A: SELECT
    Query2.username
  , Sum(Query2.SomVanpoint) AS point
FROM
    (SELECT
            test.username
          , test.level
          , Sum(test.point) AS SomVanpoint
        FROM
            test
        INNER
        JOIN
            (SELECT
                    test.username
                  , test.level
                  , Max(test.created_date) AS MaxVancreated_date
                FROM
                    test
                GROUP
                    BY test.username
                  , test.level
            ) AS Query1
            ON
            (test.username         = Query1.username)
            AND (test.level        = Query1.level)
            AND (test.created_date = Query1.MaxVancreated_date)
        GROUP
            BY test.username
          , test.level
        HAVING
            (((Sum(test.point))<= 5))
    ) AS Query2
GROUP
    BY Query2.username
HAVING
    (((Sum(Query2.SomVanpoint))< 10))
ORDER
    BY Sum(Query2.SomVanpoint) DESC;

=== output:
username  | point
----------+------
name_d    |  8
name_b    |  5
name_a    |  3

A: OK, taking part 2 first....
SELECT *
FROM table a
WHERE NOT EXISTS (
   SELECT 1
   FROM table b
   WHERE b.username=a.username
   AND a.created_date>b.created_date
)

But mysql doesn't cope with push-predicates very well, hence the max-concat trick, but that's going to make the query very complicated - worth revisiting if you've got performance problems. Now to add in the other stuff....parts 1,3 and 5
SELECT username, level, SUM(point)
FROM
(SELECT *
   FROM table a
   WHERE NOT EXISTS (
      SELECT 1
      FROM table b
      WHERE b.username=a.username
      AND a.created_date>b.created_date
   )
) ilv
GROUP BY username, level
HAVING SUM(point) <= 5;

How you implement 4 depends on the exact sequence in which this constraint is applied in relation to the other constraints (particularly 2 and 5). The following should give the disred output from the stated input...
SELECT username, level, SUM(point)
FROM
(SELECT *
   FROM table a
   WHERE NOT EXISTS (
      SELECT 1
      FROM table b
      WHERE b.username=a.username
      AND a.created_date>b.created_date
   )
) ilv,
(SELECT username, SUM(point) as totpoint
  FROM table c
  GROUP BY username
  HAVING SUM(point)<=10) ilv2
WHERE ilv.username=ilv2.username
GROUP BY username, level
HAVING SUM(point) <= 5;

Whoops - just read this again and saw that you're not interested to see a level breakdown in the output set - in which case Robin's answer is better.


text:
Q: How do I parse a string based on a certain number of characters in the string in C++? I know how to parse a string based on a delimiter, such as a comma. Does this require turning the string into an array of char?
I am wanting to compare a string that is 6 numebrs i.e. 111222
with another string of numbers that is 12 characters long but I only want the first six.
Basically way to check that 111222 occurs in the string 111222345678.

A:
....but I only want the first six

For first n chars comparison you can use std::strncmp
char s1[] ="111222345678" ;
char s2[] ="111222";

std::cout << std::strncmp( s1,s2, 6 ) ; // n =6 chars

A: using std::string, you could do
std::string sample = "111222345678";

if (sample.substr(0, 6) == "111222")
{
   ... do stuff here if ...
}

Of course, this can be made more generic by having the string to match as a std::string too:
std::string match = "111222";
if (sample.substr(0, match.length()) == match))
{
  ...
}


text:
Q: How do I make an enemy damage me instead of killing me? I'm using OpenGl and C.
I want the player to lose some health, when he gets in the vicinity of the enemy, but only lose the health once. Then if the player leaves that vicinity and comes back he loses the rest of the health. There is a global variable pHealth =100;
void damage()
{
    int dmg =50;
    pHealth-=dmg;
    if(pHealth ==0)
        {
            gameState=4;
        }
}

void drawSprite()
{
    int x;
    int y;
    int s;
    if(px<sp[0].x+30 && px>sp[0].x-30&& py<sp[0].y+30&&py>sp[0].y-30) // pick up key
        {
            sp[0].state=0;
        }
        if(px<sp[1].x+30 && px>sp[1].x-30&& py<sp[1].y+30&&py>sp[1].y-30) // enemy damage
        {
            damage();

        }

This just kills me instantly please help

A: This doesn't really have to do with opengl. Currently the player takes damage at every loop iteration (ie every frame), if they're in the vincinity of the enemy. This results in them almost instantly losing all their health (there should be at least 20~60 frame in a second, so the hp loss is almost instantaneous).
You need to ensure the player loses their health only once. For that, two possibilities:

*

*Push back the player when they encounter the enemy, so that they only spend one frame there.

*have a variable "has the player already taken the damage?". Set it to FALSE at the beginning, then when the player takes damage, set it to TRUE, and while it is true, don't give more damage to the player. When the player gets away from the enemy, reset it to False so they'll take damage again if they get close again

EDIT:
There is also solution 3

*Limit the damage rate. It means instead of checking and giving damage at every frame, you could check it every 1/10 second. Thus you could limit the damage rate


text:
Q: hamburger menu (css only) not clickable i created a hamburger menu using css only
/*based on this*/ <input type="checkbox" class="toggler">

and the toggle is not clickable
(i searched a lot and most questions/answers/problems deal with js/jquery based hamburger menu )
tutorial https://www.youtube.com/watch?v=DZg6UfS5zYg
similar code on StackOverflow  https://stackoverflow.com/a/60157218/12919436
i have included a video background
code

:root {
    --primary-color: rgba(13, 110, 139, 0.75);
    --overlay-color: rgba(24, 39, 51, 0.85);
    --menu-speed: 0.75s;
}

*{
    box-sizing: border-box;
  }

  body{
    margin:0;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-size:1rem;
    font-weight:normal;
    line-height:1.5;
    color:#333;
    overflow-x:hidden;
  }

  .v-header{
    height:100vh;
    display:flex;
    align-items:center;
    color:#fff;
  }

  .container{
    max-width:960px;
    padding-left:1rem;
    padding-right:1rem;
    margin:auto;
    text-align:center;
  }

  .fullscreen-video-wrap{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100vh;
    overflow:hidden;
  }

  .fullscreen-video-wrap video{
    min-height:100%;
    min-width:100%;
  }

  .header-overlay{
    height:100vh;
    position: absolute;
    top:0;
    left:0;
    width:100vw;
    z-index:1;
    background:#fffcb7;
    opacity:0.65;
  }

  .header-content{
    z-index:2;
  }

  .header-content h1{
    font-size:50px;
    margin-bottom:0;
  }

  .header-content p{
    font-size:1.5rem;
    display:block;
    padding-bottom:2rem;
  }

  .btn{
    background: #34b3a0;
    color:#fff;
    font-size:1.2rem;
    padding: 1rem 2rem;
    text-decoration: none;
  }

  .section{
    padding:20px 0;
  }

  .section-b{
    background:#333;
    color:#fff;
  }

  @media(max-width:960px){
    .container{
      padding-right:3rem;
      padding-left:3rem;
    }
  }

.menu-wrap{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
}

.menu-wrap .toggler{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    cursor: pointer;
    width: 50px;
    height: 50px;
    opacity: 0;
}

.menu-wrap .hamburger{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 60px;
    height: 60px;
    padding: 1rem;
    background: var(--primary-color) ;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.4s ease;
}

/*Hamburger Line*/
.menu-wrap .hamburger > div{
    position: relative;
    width: 100%;
    height: 2px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
}
 /* top and bottom lines*/
.menu-wrap .hamburger > div::before,
.menu-wrap .hamburger > div::after {
    content: '';
    position: absolute;
    z-index: 1;
    top: -10px;
    width: 100%;
    height: 2px;
    background: inherit;
}

/* Moves line down */
.menu-wrap .hamburger > div:after {
    top: 10px;
}
/* Toggler Animation */
.menu-wrap .toggler:checked + .hamburger > div {
    transform: rotate(135deg);
    z-index: 1;
  }

  /* Turns Lines Into X */
  .menu-wrap .toggler:checked + .hamburger > div:before,
  .menu-wrap .toggler:checked + .hamburger > div:after {
    top: 0;
    transform: rotate(90deg);
  }

/* Rotate On Hover When Checked */
.menu-wrap .toggler:checked:hover + .hamburger > div {
    transform: rotate(225deg);
  }

  /* Show Menu */
  .menu-wrap .toggler:checked ~ .menu {
    visibility: visible;
  }

  .menu-wrap .toggler:checked ~ .menu > div {
    transform: scale(1);
    transition-duration: var(--menu-speed);
  }

  .menu-wrap .toggler:checked ~ .menu > div > div {
    opacity: 1;
    transition:  opacity 0.4s ease 0.4s;
  }

  .menu-wrap .menu {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    visibility: hidden;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .menu-wrap .menu > div {
    background: var(--overlay-color);
    border-radius: 50%;
    width: 200vw;
    height: 200vw;
    display: flex;
    flex: none;
    align-items: center;
    justify-content: center;
    transform: scale(0);
    transition: all 0.4s ease;
  }

  .menu-wrap .menu > div > div {
    text-align: center;
    max-width: 90vw;
    max-height: 100vh;
    opacity: 0;
    transition: opacity 0.4s ease;
  }

  .menu-wrap .menu > div > div > ul > li {
    list-style: none;
    color: #fff;
    font-size: 1.5rem;
    padding: 1rem;
  }

  .menu-wrap .menu > div > div > ul > li > a {
    color: inherit;
    text-decoration: none;
    transition: color 0.4s ease;
  }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/menu.css">
    <title>blog</title>

       <input type="checkbox" class="toggler">

Home

Blog

About

Contact

   <input type="checkbox" class="toggler">

            <video src="video.mp4" autoplay="true" loop="true"></video>

Welcome

 welcome to the world of life and every
                minute detail of being you and the best version of your being

             Read More

A: Change the .menu-wrap with following:
.menu-wrap{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10;
}

A: Your header overlay is covering your button,
Set a z-index lower on it and you're good
.header-overlay{
    /* z-index: 1; Original line in your code*/
    z-index: 0;
}

A: You have two solutions:
Solution 1:
Let menu-wrap element have a z-index higher than header-overlay z-index
.menu-wrap {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2;
}

Solution 2:
Add position:relative; z-index:0; to your header so it will become layer under the menu wrap:
.container{
   position: relative;
   z-index: 0;
}


text:
Q: dataset for apriori algorithm not able to convert into csv I went to this site fimi.ua.ac.be/data/ and downloaded the retail data set.
I tried everything to convert it into .csv but I couldn't get the format of csv.
Can anyone help me to convert this retail data set file into csv?
Please help.Thanks.

A: It's a space separated file. You have two options: 1) convert it to comma separated , or 2) set your csv opening tool to open a space separated file instead of a comma separated.
If you are on *nix (unix, linux etc.) system option 1) is easier. You can achieve that by using this command:
sed 's/ /,/g' retail.dat > CSV_Retail.dat
If you are on windows option 2) is easier and MS office excel sheet has an option of reading a file separted by spaces instead of comma (or using the space delimiter)


text:
Q: Pipeline | in bash usage? I am learning BASH, my problem is the following.
I'm decompressing a file using tar -zxvf, this returns a (what I think) is a list type ls -l from the folder it has been extracted.
What I want to do is take the first object of it using head -1.
I can do this, but to keep my code clean I would like to do it using pipeline.
This works:
filename_2=$(tar zxvf ${filename})
echo "${filename_2}" | head -1

This doesn't (it returns an empty string):
filename_2=$(tar zxvf ${filename}) | head -1
echo "${filename_2}"

Am I understanding the pipeline concept wrong? I thought that it simply took the input from the last function as input of the last one, if so, why do I need to do it in two separate lines?
Thanks

A: You don't need the variable at all. Pass the output of tar directly to head.
tar zxvf "$filename" | head -1

If you then wanted to save that result in a variable you'd write:
filename_2=$(tar zxvf "$filename" | head -1)
echo "$filename_2"


text:
Q: How to trigger and event with parameter value using jquery I want to show a parameter value when a user mouseover it. I want to do it with jquery. My function is returning an undefined value.

HTML:

show info

A: I would suggest to do it slightly differently:

show info

And jQuery:
$(document).ready(function() {
  $("#showInfo").mouseover(function() {
    showInfo($(this).attr("id"), '50', '60');
  });
});

function showInfo(id, a, b) {
  var html = '
'+a+'

'+b+'
';
  $("#container").append(html);
}

You can also have a look on hover function of jQuery.
jsFiddle here: http://jsfiddle.net/KvMuD/

A: You had some syntax errors :

A: function showInfo(id, a, b) {
  var html = '
'+a+'

'+b+'
';
  $(body).append(html);
}

Then:

show info

Would be a cleaner version. But it's not clear why you are passing the actual div you are hovering over into the function. What do you want to do with it?


text:
Q: get result in descending order of 3 joined table Query code is:
$output="SELECT firstname, cnumber, raddress,pincode,state,country,heducation,ssc,practiceone,addressone,daysone,image
    FROM doctor
    JOIN addprofile ON doctor.id=addprofile.login_id
    JOIN consultation ON doctor.id=consultation.login_id
    ORDER BY id DESC";

Question is:
How to get result in descending order of 3 joined table with primary id of first table?
Thanks in advance.

A: Suggested re-write:
ORDER BY doctor.id DESC


text:
Q: Azure pipeline to build public github project, pipeline yaml stored in Azure Devops Git I want to create a pipeline which builds and packages a public/opensource codebase from a public github repo.
I don't want to store the pipeline yaml definition github, I want this in my private Azure Devops repo.
Basically I want the pipeline to:

*

*clone the public git repo

*perform a build

*do some configuration and packaging

*deploy it

It seems like Azure yaml pipelines expect the pipeline yaml and code to exist in the same repository. I see tasks types to download a "GitHub Release", but nothing to just generically clone a git repo. Am I missing it?

A: To save the Pipeline Yaml file in Private Azure DevOps repo and use repo from Github, you need to reference multiple repo resouces in YAML.
Here are two methods you can refer to:
You can add the Repo Resource in YAML pipeline to use the repo in Github. Refer to this doc:Check out multiple repositories in your pipeline
For example:
resources:
  repositories:
  - repository: MyGitHubRepo
    type: github
    endpoint: MyGitHubServiceConnection
    name: MyGitHubOrgOrUser/MyGitHubRepo

steps:
- checkout: self
- checkout: MyGitHubRepo

- script: dir $(Build.SourcesDirectory)

Or you can add a step to run the git clone command to clone the public git repo.
steps:
- script: git clone RepoURL
  displayName: 'Clone Github Repo'

- other tasks to build the project

In this case, the YAML file will be saved in Azure Repo. And the Github Repo will be checked out during the pipeline run.


text:
Q: best practice in drawing outline of image I've tried 3 ways to make it, but the effect doesn't looks well.

*

*copy and fill image then make offset. The demo is

var ctx = canvas.getContext('2d'),
    img = new Image;

img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";

function draw() {

  var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
      s = 20,  // thickness scale
      i = 0,  // iterator
      x = 5,  // final position
      y = 5;

  // draw images at offsets from the array scaled by s
  for(; i < dArr.length; i += 2)
    ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);

  // fill with color
  ctx.globalCompositeOperation = "source-in";
  ctx.fillStyle = "red";
  ctx.fillRect(0,0,canvas.width, canvas.height);

  // draw original image in normal mode
  ctx.globalCompositeOperation = "source-over";
  ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>

. When the outline width is large, the outline result will be wrong.

*check the edge of image base on the Marching Squares algorithm. When the image shape is circle, the outline is with sawtooth. If make the outline more smoother, it won't fit the sharp shape like star.

*copy and fill the image then scale it. When a image width is not equal with height, it doesn't work.

A: You can try with a math approach, without the offset array

var ctx = canvas.getContext('2d'),
  img = new Image;

img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";

function draw() {
  var s = 20, // thickness scale
    x = 5, // final position
    y = 5;

  for (i=0; i < 360; i++)
    ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);

  // fill with color
  ctx.globalCompositeOperation = "source-in";
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // draw original image in normal mode
  ctx.globalCompositeOperation = "source-over";
  ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>

My idea comes from the way we draw a circle using a string:
https://www.wikihow.com/Draw-a-Perfect-Circle-Using-a-Pin
Imagine that instead of a pencil at the end of the string we just have a shape

Here is a visual comparison of my approach and yours, also I'm showing a third approach scaling the image, there is really not a best one, it's just a matter of personal preference.

You could create a hybrid mode, if the hairline is important to you, get that portion of the image scaling it, then use a different way for the rest of the body.


text:
Q: Android custom image in status bar while audio is playing I am trying to figure out a way to have a custom image display in the status bar of an Android device whenever audio is being played (independent of the app used to invoke the audio). I am not referring to an app or a notification, but rather I need this to happen on a system-wide level. From the research I've done I have found that this can not be done through the Android SDK and I will most likely have to create a custom ROM to do this. However I do not know if this is the correct solution and if it is, how would I get started? Thanks in advance!

A: AFAIK the music icon in the notification is provided by the music app not the system...
One way of knowing this is try different music apps,  and check if u are getting same icon in notification...
If yes then you can easily change that icon, u need to be rooted of course...
Pull out framework-res.apk from /system/framework.
Extract it using 7-zip.
Go to folder /res/drawable-xxxx (where xxxx indicate your screen size like hdpi, mdpi, ldpi etc)
Then look for the icon that u saw in notification, renane your custom icon with the same name...
Replace it in 7-zip at that location with custom icon of same size, resolution n extension...


text:
Q: Open Android installed applications screen (app drawer) programmatically Is there a way (maybe a workaround) to open the Android installed applications screen programmatically?  More than that I want to open the widgets page, but not sure if is possible.
I've tried in this way:
Intent pickIntent = new Intent(Intent.ACTION_ALL_APPS);
pickIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
pickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(pickIntent);

but Intent.ACTION_ALL_APPS actually lists all available applications and using this is closing my app.

A: You can try like link to open the installed application page like a list..
Also can see the answer form here


text:
Q: pymssql executemany insert valueerror I get an error:

File "pymssql.pyx", line 443, in pymssql.Cursor.executemany
  (pymssql.c:6616)   File "pymssql.pyx", line 417, in
  pymssql.Cursor.execute (pymssql.c:6057)   File "_mssql.pyx", line 943,
  in _mssql.MSSQLConnection.execute_query (_mssql.c:9858)   File
  "_mssql.pyx", line 974, in _mssql.MSSQLConnection.execute_query
  (_mssql.c:9734)   File "_mssql.pyx", line 1091, in
  _mssql.MSSQLConnection.format_and_run_query (_mssql.c:10814)   File "_mssql.pyx", line 1113, in _mssql.MSSQLConnection.format_sql_command
  (_mssql.c:11042)   File "_mssql.pyx", line 1797, in
  _mssql._substitute_params (_mssql.c:18646) ValueError: more placeholders in sql than params available

while executing bulk insert into mssql table (executemany). Inserting the same data in one execute statemend as well as in mssql management studio works just fine.
I tried executemany (data) with dictionary and a tuple - same result.
The code:
cursor.executemany("insert table Values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (data))

Any ideas?

A: All sublists/subtuples in data should have length 21 (the number of %s in your SQL query).
But. Your data have also items with length 11, 12, 13, 15, 16, 17, 18, 19, and 20.
And you get the error more placeholders (meaning: %s) in sql than params (meaning: sublists in data) available
To fix: check how you're generating data and mercilessly twenty-one every data item.


text:
Q: Chapter heading in Word is not the same I set Heading 1 style for the chapter heading in Word. The style is as follows: Paragraph before 72 and after 54. I also use the word "Chapter" before the number of the chapter.
So if I place the cursor at the beginning of the page and click the Heading 1 style, it will look like:

Chapter 1 (Shift+Enter)
Introduction
(Texts)...

Now, at the end of Chapter 1, I insert a page break and a blank page appears. I click Heading 1 again, and it shows:

Chapter 2
Literature Review

Note that the words "Introduction" and "Literature Review" are entered manually.
My question is, I expect Chapter 2 will follow the paragraph style that I defined (i.e. Before 72, after 54) but it doesn't. Chapter 2 is displayed at the very top without following the Heading 1 paragraph style. Other settings like font are OK.
How do you deal with this problem? I tried to manually set this paragraph style, but the Chapter 2 is always displayed without the 'before' and 'after ' style.
Thank you.

A: Word 2010 suppresses space above headings at the top of the page, if they come after a Page Break (shift+enter).
If instead you use Section Break (Next Page) in Page Layout > Breaks > Next Page, then the space should not be suppressed before the Chapter 2 heading.


text:
Q: Python Rock Paper Scissor bug I don't understand I am working on a rock paper scissor game in Python, and I was quite happy with the result below until I noticed I get the "Not a valid answer" case with the following:
player1 = p and player2 = s
player1 = s and player2 = r
I can't figure out why those cases do not work regarding the code logic below. Other combinations with the same letters work fine for both players.
What did I do wrong?
(I'm using jupyter on anaconda)
scoreP1 = 0
scoreP2 = 0
game = True
while game != 'QUIT':
    player1 = input("\nJanken! Player 1, type 'r' for Rock, 'p' for Paper or 's' for Scissor: ")
    player2 = input("Janken! Player 2, type 'r' for Rock, 'p' for Paper or 's' for Scissor: ")
    if(
        (player1=="r" and player2=="s") or
        (player1=="p" and player2=="r") or
        (player1=="s" and player2=="p")
    ):
        print("\nPlayer 1 wins! Congrats! Updating scores...")
        scoreP1+=1
        print("Score player 1:",scoreP1)
        print("Score player 2:",scoreP2)
    elif(
        player1==player2
    ):
        print("\nTie! Updating scores...")
        print("Score player 1:",scoreP1)
        print("Score player 2:",scoreP2)

    elif(
        player1 != "r" or
        player1 != "s" or
        player1 != "p" or
        player2 != "r" or
        player2 != "s" or
        player2 != "p"
    ):
        print("\nNot a valid answer. Please type 'r' for Rock, 'p' for Paper or 's' for Scissor.")
    else:
        print("Player 2 wins! Congrats! Updating scores...")
        scoreP2+=1
        print("Score player 1:",scoreP1)
        print("Score player 2:",scoreP2)
    game = input("\nAnother game? Type 'QUIT' to end this, or anything else to continue:")

A: The problem is that for a result that should return "Player 2 wins" (eg player1=="s" and player2=="r") ,  the invalid if block matches:
player1 != "r" or
player1 != "s" or
player1 != "p" or
player2 != "r" or
player2 != "s" or
player2 != "p"

You probably meant
( player1 != "r" and player1 != "s" and player1 != "p" )
or ( player2 != "r" and player2 != "s" and player2 != "p" )

or, more pythonic:
 player1 not in ["s", "p", "r"] or player2 not in ["s", "p", "r"]

A: elif(
    player1 != "r" or
    player1 != "s" or
    player1 != "p" or
    player2 != "r" or
    player2 != "s" or
    player2 != "p"
):

This code block requires one of the lines to be True, in order for the whole elif to be true.
If player1 == 's', the code will say "s is not equal to r" Therefor this list of 'or'-statements must be True.

A: In your last elif you are testing if player1 or player2 is different from your accepted answers.
if (player1 != "r" or player1 != "s"...)

This is TRUE because if it is "r" it is not "s", if it is "s" then it is != "r" etc.
You should use AND instead of OR when testing if it did not belong in ANY of thiese.
Replace those OR with AND and you should be fine.

A: I think this should be broken down so the evaluation can be properly examined. Take a simpler view of the elif condition:
player1 != "r" or player1 != "s"

Now say, the letter "s" is assigned into player1. That above condition evaluates as:
"s" != "r" or "s" != "s"  # Substitute in the value in the place of player1
True or False             # The first half becomes true, the second false
True                      # Which ends up as true

Now say, the letter "r" is assigned into player1. That top condition evaluates as:
"r" != "r" or "r" != "s"  # Substitute in the value in the place of player1
False or True             # The first half becomes false, the second true
True                      # Which ends up as true

Note how the result is true again. This condition will always be true. For it to be false, you would have to end up with
False or False

In the second step of the evaluation, and that isn't possible. player1 would need to be equal to both "s" and "r" at the same time, which, beyond __eq__ hacks to make a bizarrely behaving object, isn't possible.

When in doubt, think up some sample data, plug it in, and see how it evaluates like I showed above. It's great practice, and always helpful while debugging conditions like this.

A: player1 != "r" or
player1 != "s" or
player1 != "p" or
player2 != "r" or
player2 != "s" or
player2 != "p".

not only prevents illegal input, it prevents legal input too.
player1 = p and player2 = s

player1 = s and player2 = r

both match the condition.


text:
Q: Managing References in Visual Studio 2012 Please help me understand: I have a Visual Studio project. It has Nuget package manager enabled. I install several libraries. The library versions are shown in packages.config. Each library has a corresponding entry in References.
Now, say I want to change the library version from, say, 2.2.0 to 2.1.0. How I do this? At first I assumed you could just change the version number in packages.config. But when I do this, and get Nuget to download an earlier version of the library, the project references are not changed.
Do I have to manually remove each and every reference in the project to 2.2.0 and replace it with 2.1.0?
I get the feeling I'm "doing it wrong", but there doesn't seem to be any examples I can find of anyone doing it right.
Thanks for any help!

A: Using jQuery as an example:
If you want to rollback to a previous version you can run the Uninstall-Package jQuery and Install-Package jQuery -Version 2.1.0 commands from the package manager console.
Also, the package nuget page will have a list off all the versions available. EX: jQuery
All of this and more available in the nuget Docs

A: You can't simply change the version in the config file since your project still holds a reference to the binaries, so the binaries need to be replaced too.
Now, I'm not entirely sure if there is a "downgrade" Powershell command but you can certainly uninstall the specific package and then install a lower version. By using the Package Manager Console. So from within Visual Studio:

*

*Go to the View menu -> Other Windows -> Package Manager Console

*Select the Default Project from the dropdown list

*Then run the following command to uninstall the package

The command to uninstall is...
Uninstall-Package YOUR_PACKAGE_NAME

To install a lower version, run this command...
Install-Package YOUR_PACKAGE_NAME -Version 1.0

These and other commands are very well documented in The Package Manager Console Powershell Reference
Uninstall-Package Command
Install-Package Command


text:
Q: Sequential power circuit for 18 servos I'm trying to design a servo control board to be a daughter card for DE0-NANO, but run into a problem where all the servos (18 for hexapod) get to the end position on power up.
The initial idea was to implement 'power on reset' circuit, but i was told it a bad idea.
Im looking for some suggestion as to how i can achieve a sequential start up for each leg of the robot. I was thinking maybe some digitally controlled relays or a separate little micro-controller or maybe somebody has a better idea?????

A: Solved the problem, should have posted it a while ago...
Anyway, fount some omnifets, which are a pair per IC works well in tests, havent actually put the whole circuit together. Also placing a capacitor between the power terminals solved the debounce issue.
Here is a link to the mosfets:
 http://uk.rs-online.com/web/p/intelligent-power-switches/8773144/


text:
Q: 'post method not allowed' error while sending data to php with ajax I want to send some data to php to change something in my MySQL database, but I keep getting this 405 error 'POST method not allowed'. I googled a lot, but can't find any useful solution. Can someone explain to me what I'm doing wrong?
I'm using Razor inside HTML to render the data on the webpage:
@foreach(var row in db.Query(getKamers))
     {
        <form id="@row.id" action='_DataConn.php' method='post' class='ajaxform'>
            <input type="text" value="@row.id" name="id" id="td-id" />
            <input type="text" value="@row.oppervlakte" name="oppervlakte" id="td-opp" />
            <input type="text" value="@row.locatie" name="locatie" id="td-loc" />
            <input type="text" value="@row.type" name="type" id="td-type" />
            <input type="text" value="@row.kamernr" name="nummer" id="td-kamernr" />
            <input type="text" value="@row.vrij" name="vrij" id="td-vrij" />
            <input type="submit" value="opslaan" name="opslaan" id="@row.id" />
        </form>
     }

then I have this JavaScript file:
$(document).ready(function () {
$('.ajaxform').submit(function () {
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {
            console.log(data);
        }
    });

    return false;
});

});
and my PHP looks like this:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "Studentenkamers";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String

$id = $_POST['id'];
$oppervlakte = $_POST['oppervlakte'];
$locatie = $_POST['locatie'];
$kamernr = $_POST['nummer'];
$type = $_POST['type'];
$vrij = $_POST['vrij'];
echo 'ok'
// Escape User Input to help prevent SQL Injection

$id = mysql_real_escape_string($id);
$oppervlakte = mysql_real_escape_string($oppervlakte);
$locatie = mysql_real_escape_string($locatie);
$kamernr = mysql_real_escape_string($kamernr);
$type = mysql_real_escape_string($type);
$vrij = mysql_real_escape_string($vrij);
//build query
//"UPDATE Studentkamer SET oppervlakte='" + room[1] + "', locatie='" + room[2] + "', type='" + room[3] + "', vrij='" + room[4] + "' WHERE id='" + room[0] + "'";
$query = "UPDATE Studentkamer SET oppervlakte = '$id', locatie = '$locatie', type='$type', kamernr   = '$kamernr', vrij = '$vrij' WHERE id='$id'";

//Execute query
 $qry_result = mysql_query($query) or die(mysql_error());
 ?>

EDIT:
Below is the link to a screenshot of the error info, does it has something to do with the static context?
http://img41.imageshack.us/img41/9139/errorde.jpg
I am working in Webmatrix using localhost, do I need to put this website online for it to work?

A: Look at the submit button and form id. Does the razor translate that into a valid string? It looks to me as if the ids contain @. The @ in the id values is not permitted according to http://www.w3.org/TR/html4/types.html. This might be passed as values containing those characters
    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number
 of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Try
@(row.id)
Reference - MVC3 Razor syntax. How do I convert this ASP.NET style to Razor. (also issues with @ within quotes)

A: You have to allow POST method in config for your web-server


text:
Q: Eclipse: create Gradle project but make Eclipse "accept" Groovy for app files I've got the dreaded red exclamation mark after creating a Gradle project and adding a .groovy file under src/main/groovy/myPackage/
I've been using Eclipse (currently 2020-09) for years and I think I'm on fairly firm ground when I say that this is about build path configuration errors.
I can build and run this project at the command line (i.e. outside Eclipse) using the Gradle wrapper. The opening lines of build.gradle look like this:
plugins {
    // Apply the java-library plugin to add support for Java Library
    id 'java-library'

    id 'eclipse'

    id 'application'

    id 'groovy'

    id 'org.openjfx.javafxplugin' version '0.0.8'
}
mainClassName = 'gpackage.Gtest'

But there is no "Groovy" entry under Project --> Properties. Although under Window --> Preferences there is a Groovy entry, as I did this Groovy-Eclipse setup: https://stackoverflow.com/a/48083451/595305 (snapshot update site https://dist.springsource.org/snapshot/GRECLIPSE/e4.17).
If you start off by making a "Groovy Project" as opposed to a "Gradle Project", your Project --> Properties do include a "Groovy" entry. Is there any way to configure things to add this entry to a project started as a Gradle project?

A: Well I found one answer... this may or may not be the way to do it:
Right-click on project in Package Explorer --> Configure --> Convert to Groovy project.
This has got rid of the exclamation mark. The Gradle views (Gradle Executions and Gradle Tasks) have disappeared... but these can be added back.
Project --> Properties now includes an entry "Groovy Compiler".
But... I now find that, for example, I'm getting the nasty "white cross in a red box" next to many of my import statements in the Groovy file, e.g. JavaFX import statements. Despite having the javafxplugin (see above) and also the following lines in the build.gradle file:
javafx {
    version = "13"
    modules = [ "javafx.controls", "javafx.fxml" ]
}

... I thought at first that this problem had arisen since I converted to a Groovy project, but it seems that the nasty red exclamation mark was in fact concealing the nasty white-crosses-in-red-boxes.
Edit
Setting up the JavaFX so that Eclipse error marks disappear is a bit of a rigmarole, but I find I documented this sufficiently after struggling for days about a year ago. It involves creating an Eclipse "User Library" containing the .jar files under /lib when you download and uncompress the JavaFX .zip, and then adding this library to the project's module path. More details can be supplied: add a comment.


text:
Q: ThreadLocalRandom with shared static Random instance performance comparing test In our project for one task we used static Random instance for random numbers generation goal. After Java 7 release new ThreadLocalRandom class appeared for generating random numbers.
From spec:

When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.

and also:

When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.

So I've made my little test:
public class ThreadLocalRandomTest {

private static final int THREAD_COUNT = 100;
private static final int GENERATED_NUMBER_COUNT = 1000;
private static final int INT_RIGHT_BORDER = 5000;
private static final int EXPERIMENTS_COUNT = 5000;

public static void main(String[] args) throws InterruptedException {
    System.out.println("Number of threads: " + THREAD_COUNT);
    System.out.println("Length of generated numbers chain for each thread: " + GENERATED_NUMBER_COUNT);
    System.out.println("Right border integer: " + INT_RIGHT_BORDER);
    System.out.println("Count of experiments: " + EXPERIMENTS_COUNT);

    int repeats = 0;
    int workingTime = 0;
    long startTime = 0;
    long endTime = 0;

    for (int i = 0; i < EXPERIMENTS_COUNT; i++) {
        startTime = System.currentTimeMillis();
        repeats += calculateRepeatsForSharedRandom();
        endTime = System.currentTimeMillis();
        workingTime += endTime - startTime;
    }
    System.out.println("Average repeats for shared Random instance: " + repeats / EXPERIMENTS_COUNT
            + ". Average working time: " + workingTime / EXPERIMENTS_COUNT + " ms.");

    repeats = 0;
    workingTime = 0;
    for (int i = 0; i < EXPERIMENTS_COUNT; i++) {
        startTime = System.currentTimeMillis();
        repeats += calculateRepeatsForTheadLocalRandom();
        endTime = System.currentTimeMillis();
        workingTime += endTime - startTime;
    }
    System.out.println("Average repeats for ThreadLocalRandom: " + repeats / EXPERIMENTS_COUNT
            + ". Average working time: " + workingTime / EXPERIMENTS_COUNT + " ms.");
}

private static int calculateRepeatsForSharedRandom() throws InterruptedException {
    final Random rand = new Random();
    final Map<Integer, Integer> counts = new HashMap<>();

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {

                for (int j = 0; j < GENERATED_NUMBER_COUNT; j++) {
                    int random = rand.nextInt(INT_RIGHT_BORDER);
                    if (!counts.containsKey(random)) {
                        counts.put(random, 0);
                    }
                    counts.put(random, counts.get(random) + 1);
                }
            }
        };
        thread.start();
        thread.join();
    }

    int repeats = 0;
    for (Integer value : counts.values()) {
        if (value > 1) {
            repeats += value;
        }
    }

    return repeats;
}

private static int calculateRepeatsForTheadLocalRandom() throws InterruptedException {
    final Map<Integer, Integer> counts = new HashMap<>();

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {

                for (int j = 0; j < GENERATED_NUMBER_COUNT; j++) {
                    int random = ThreadLocalRandom.current().nextInt(INT_RIGHT_BORDER);
                    if (!counts.containsKey(random)) {
                        counts.put(random, 0);
                    }
                    counts.put(random, counts.get(random) + 1);
                }
            }
        };
        thread.start();
        thread.join();
    }

    int repeats = 0;
    for (Integer value : counts.values()) {
        if (value > 1) {
            repeats += value;
        }
    }

    return repeats;
}

}
I've also added test for non-shared Random and got next results:
Number of threads: 100
Length of generated numbers chain for each thread: 100
Right border integer: 5000
Count of experiments: 10000
Average repeats for non-shared Random instance: 8646. Average working time: 13 ms.
Average repeats for shared Random instance: 8646. Average working time: 13 ms.
Average repeats for ThreadLocalRandom: 8646. Average working time: 13 ms.

To me it's little strange, as I expected at least speed increasing when using ThreadLocalRandom comparing to shared Random instance, but see no difference at all.
Can someone explain why it works that way, maybe I haven't  done testing properly. Thank you!

A: Your testing code is flawed for one. The bane of benchmarkers everywhere.
thread.start();
thread.join();

why not save LOCs and write
thread.run();

the outcome is the same.
EDIT: If you don't realize the outcome from the above, it means that you're running single threaded tests, there's no multithreading going on.

A: You're not running anything in parallel because you're waiting for each thread to finish immediately after starting it. You need a waiting loop outside the loop that starts the threads:
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < THREAD_COUNT; i++) {
    Thread thread = new Thread() {
        @Override
        public void run() {

            for (int j = 0; j < GENERATED_NUMBER_COUNT; j++) {
                int random = rand.nextInt(INT_RIGHT_BORDER);
                if (!counts.containsKey(random)) {
                    counts.put(random, 0);
                }
                counts.put(random, counts.get(random) + 1);
            }
        }
    };
    threads.add(thread);
    thread.start();
}

for (Thread thread: threads) {
    thread.join();
}

A: Maybe it would be easier to just have a look at what actually happens. Here is the source for ThreadLocal.get() which is also called for the ThreadLocalRandom.current().
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null)
            return (T)e.value;
    }
    return setInitialValue();
}

Where ThreadLocalMap is a specialized HashMap-like implementation with optimizations.
So what basically happens is that ThreadLocal holds a map Thread->Object - or in this case Thread->Random - which is then looked up and either returned or created. As this is nothing 'magical', the timing will be equal to a HashMap-lookup + the initial creation overhead of the actual Object to be returned. Since a HashMap lookup (in this optimized case) is linear, the cost for a lookup is k, where k is the calculation cost of the hash function.
So you can make some assumptions:

*

*ThreadLocal will be faster than creating the object each time in each Runnable, unless the creation cost is much smaller than k. So looking up Random is a good thing, putting an int inside might not be so smart.

*ThreadLocal will be better than using your own HashMap, as such a generic implementation can be assumed to be equal to k or worse.

*ThreadLocal will be slower than using any lookup with a cost < k. Example: store everything in an array first, then do myRandoms[threadID].
But then this assumes that you know which threads will be processing your work in the first place, so this isn't a real candidate for ThreadLocal anyways.


text:
Q: perl: grep and map in one operation Is there a way to perform a grep and a map in a single operation in perl?  Similar to the way that python can perform list comprehension:
files = [{ 'path':'/path/to/file1',
           'size':123},
         { 'path':'/path/to/file2',
           'size':987},
         { 'path':'/path/file3',
           'size':1234},
         { 'path':'/path/to/file4',
           'size':543},
         { 'path':'/path/to/my/file5',
           'size':1357}]
large_filepaths = [file['path'] for file in files if file['size'] > 1024]

In Perl, I need to do a grep to filter out the large files, then a map to get the specific values I want:
my $files = [ { path=>'/path/to/file1',
                size=>123},
              { path=>'/path/to/file2',
                size=>987},
              { path=>'/path/file3',
                size=>1234},
              { path=>'/path/to/file4',
                size=>543},
              { path=>'/path/to/my/file5',
                size=>1357} ];
my @large = grep { $_->{size} > 1024 } $files;
my @large_filepaths = map { $_->{path} } @large;

Is there a simple way to run this in a single operation, or do I have to use 2 statements (or one compound statement)?

A: *

*$files is an array reference, therefore values $files does not make sense.

*map BLOCK and grep BLOCK tend to be slower than map EXPR and grep EXPR, respectively. Prefer the latter if you can.
my @large_filepaths =
    map $_->{path},
    grep $_->{size} > 1024,
    @$files;

A:
Is there a simple way to run this in a single operation,

You can do it as one compound statement:
my @large_paths = map { $_->{path} } grep ...;

A: You can do this with just a call to map if you want
my @large_filepaths = map { $_->{size} > 1024 ? ( $_->{path} ) : ( ) } @$files;

but I think a combined map/grep is clearer.

A: One statement with map { ... } grep { ... } @$files is the "standard" way to do it and the closest equivalent to what you're doing in Python.
Technically it's possible to do it in a single map, because map can return any number of values for each input value, including zero — so you can do something like
map { $_->{size} > 1024 ? $_->{path} : () } @$files, but that's substantially less clear and I wouldn't recommend it in general.