text:
Q: Python (spyder) skipping lines of code in a function? I am doing a project from a bioinformatics course.
For the project we receive multiple DNA strings and an integer k. The task of the project is to find a K-mer motif that minimizes the sum of hamming distance between the motif and each DNA string.
I wrote a function MedianString(seqLines,k) for the task. In the function,  initial values for firstly assigned to a few variables, and then a for loop was included. When I call the function, python seems to skip all the lines before the loop and runs directly what's within the loop. I tried to search online for possible cause of the problem and found some similar discussions, but none of them seemed to be applicable for my case. I am pretty lost...
the lines that python skipped:
print('BBBBBBBBBBBBBB')
distance = 100000000000000000000000000000000
print('distance=')
print(distance)
Median = []
pattern = []
sumHD = 0

the lines that were run:
for i in range (0, 4**k-1):
    pattern = NumberToPattern(i,k)
    print('this is pattern')
    print (pattern)
    sumHD = sumOfMinHD(pattern,seqLines)
    print('sumHD=',type(sumHD))
    print(sumHD)
    print('distance=',type(distance))
    print(distance)
    if distance > sumHD:
        print('distance>sumOfMinHD')
        distance = sumOfMinHD(pattern,seqLines)
        Median = pattern
        print('distance=')
        print(distance)
    else:
        print('distance is <=sumOfMinHD')

the full code(pseudocode credit: Finding Hidden Messages in DNA (Bioinformatics I) by University of California San Diego):
#Code Challenge: Implement MedianString.
#Input: An integer k, followed by a collection of strings Dna.
#Output: A k-mer Pattern that minimizes d(Pattern, Dna) among all possible choices of k-mers.
#(If there are multiple such strings Pattern, then you may return any one.)
 #the concept of the code:
 #MedianString(Dna, k)
 #   distance ← ∞
 #   for each k-mer Pattern from AA…AA to TT…TT
 #       if distance > d(Pattern, Dna)
 #            distance ← d(Pattern, Dna)
 #            Median ← Pattern
 #   return Median

with open(r'D:\Users\moonc\Desktop\python_exercises_for_bioimformatics_I\MedianStringSampleInput.txt','r') as seqFile :
    DataSet = seqFile.read().splitlines()
    print ('this is Dataset')
    print (DataSet)
    seqLines = DataSet [1:]
    print ('this is seqLines')
    print (seqLines)
    print (len(seqLines))
    k = int(DataSet[0])
    print ('this is k')
    print (k)

#NumberToPattern
def NumberToPattern(number, k):
    pattern = []
    for i in range (0,k):
        if number // (4**(k-1-i)) == 0:
            pattern.append ("A")
        elif number // (4**(k-1-i)) == 1:
            pattern.append ("C")
        elif number // (4**(k-1-i)) == 2:
            pattern.append ("G")
        elif number // (4**(k-1-i)) == 3:
            pattern.append ("T")

    number = number % (4**(k-1-i))

    intToString = map(str, pattern)
    patternString = "".join(intToString)

    return patternString

#Hamming Distance Problem: Compute the Hamming distance between two strings.
#   Input: Two strings of equal length.
#   Output: The Hamming distance between these strings.

def HammingDistance(p,q):
    HD = 0
    for i in range(0,len(p)):
        if p[i] != q [i]:
           HD = HD+1

    return HD

#minHDandMotif(Pattern, Text) is the minimum Hamming distance between Pattern and any k-mer in Text

def minHDandMotif(Pattern,String):
    HD = float('inf')
    motif = []
    for i in range (0,len(String)-len(Pattern)+1):
        if HammingDistance(Pattern,String[i:i+len(Pattern)]) < HD:
            HD = HammingDistance(Pattern,String[i:i+len(Pattern)])
            motif = String[i:i+len(Pattern)]
       # print (motif)
    print ('this is minHD and Motif')
    print ([HD,motif])
    return [HD,motif]

#sumOfMinHD(Pattern, Dna) as the sum of distances between Pattern and all strings in Dna
#Dna is a collection of strings of the same length

def sumOfMinHD(Pattern,seqLines):
    sumHD = 0
    print(seqLines)
    for i in range (0,len(seqLines)-1):
        minHD = minHDandMotif(Pattern,seqLines[i])[0]
        sumHD = sumHD + minHD
    print ('this is sum Of MinHD')
    print (sumHD)
    return sumHD
######################
def MedianString(seqLines,k):
    print('BBBBBBBBBBBBBB')
    distance = 100000000000000000000000000000000
    print('distance=')
    print(distance)
    Median = []
    pattern = []
    sumHD = 0
    for i in range (0, 4**k-1):
        pattern = NumberToPattern(i,k)
        print('this is pattern')
        print (pattern)
        sumHD = sumOfMinHD(pattern,seqLines)
        print('sumHD=',type(sumHD))
        print(sumHD)
        print('distance=',type(distance))
        print(distance)
        if distance > sumHD:
            print('distance>sumOfMinHD')
            distance = sumOfMinHD(pattern,seqLines)
            Median = pattern
            print('distance=')
            print(distance)
        else:
            print('distance is <=sumOfMinHD')
    return Median
####################
Median = MedianString(seqLines,k)
print ('this is MedianString')
print (Median)

the console of the last recursion of the loop in MedianString(seqLines,k):

this is pattern
TTG
['AAATTGACGCAT', 'GACGACCACGTT', 'CGTCAGCGCCTG', 'GCTGAGCACCGG', 'AGTACGGGACAG']
this is minHD and Motif
[0, 'TTG']
this is minHD and Motif
[2, 'ACG']
this is minHD and Motif
[1, 'CTG']
this is minHD and Motif
[1, 'CTG']
this is sum Of MinHD
4
sumHD= <class 'int'>
4
distance= <class 'int'>
2
distance is <=sumOfMinHD
this is MedianString
ACC


text:
Q: Get data from another activity Still working on my skills in android.
My problem here is that i have a label from my database that contain a name that is in a spinner, when i click on the label, a dialog comes and give you three choices:
1. update.
2. delete.
3. cancel.
I got through the second and the third choices, but in the update am facing this problem;
i go to another activity that has an editText and the 2 Buttons, save and cancel, i want the save button to get the data from the editText in putExtra and send it back to the same previous activity and change the old label with the data from the editText.
I appreciate any help.
Thanks in advance.

A: You have to pass the information as extras.
Passing the Information
Intent i = new Intent();
i.setClassName("com.example", "com.example.activity");
i.putExtra("identifier", VALUE);
startActivity(i);

Getting the Information
Bundle extras = getIntent().getExtras();
String exampleString = extras.getString("identifier");

A: In your second activity, you can get the data from the first activity with the method getIntent() and then getStringExtra(), getIntExtra()...
Then to return to your first activity you have to use the setResult() method with the intent data to return back as parameter.
To get the returning data from your second activity in your first activity, just override the onActivityResult() method and use the intent to get the data.
First Activity:
//In the method that is called when click on "update"
Intent intent = ... //Create the intent to go in the second activity
intent.putExtra("oldValue", "valueYouWantToChange");
startActivityForResult(intent, someIntValue); //I always put 0 for someIntValue

//In your class
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //Retrieve data in the intent
    String editTextValue = intent.getStringExtra("valueId");
}

Second Activity:
//When activity is created
String value = intent.getStringExtra("oldValue");
//Then change the editText value

//After clicking on "save"
Intent intent = new Intent();
intent.putExtra("valueId", value); //value should be your string from the edittext
setResult(somePositiveInt, intent); //The data you want to send back
finish(); //That's when you onActivityResult() in the first activity will be called

Don't forget to start your second activity with the startActivityForResult() method.

A: When you want to start second activity, use startActivityForResult(your intent, request code);
In your first activity use
protected void onActivityResult(int requestCode, int resultCode,
             Intent data) {
         if (requestCode == your_reques_code) {
             if (resultCode == RESULT_OK) {
                 // do your stuff
             }
         }
}

Before finish second activity dont forget this,
Intent data = new Intent();
data.putExtra("text", edtText.getText());
setResult(RESULT_OK, data);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are there any naturally occurring examples of photons without mass? I read that a photon is said to have zero mass at zero velocity.
Does this mean that they only exist in a state of probability until observed && interacting with some system? And then when observed they collapse into a particle that has velocity and said mass?
Or is it possible to have a photon behaving as a particle without mass?
This feels intuitively like the "wrong question", but could someone please explain to me how a photon, if it is energy, has no mass?
Are there any naturally occurring examples of photons without mass?

A: I think there is some confusion here. Photons are always massless. They also always move at the speed of light. Therefore every example of a photon in nature has zero mass.
Perhaps you are thinking about a photon moving through a medium other than a vacuum. In this case, we can view the photon plus the interactions with the medium as a quasiparticle with a nonzero mass and a speed slightly less than the speed of light. But then we are no longer considering a true photon, so there is no contradiction with the first paragraph.
Edit:
To answer your comment, in special relativity the energy of a particle is
$$E\equiv\gamma mc^2$$
where
$$\gamma \equiv \frac{1}{\sqrt{1-v^2/c^2}}$$
When we plug $v=c$ and $m=0$ into the formula for the energy, we find that $\gamma$ goes to $\infty$. Therefore, this expression for $E$ is an indeterminate form, so it should seem reasonable that any particle with zero mass moving at the speed of light can have a finite energy.
Perhaps a more useful formula for the energy in this situation is
$$E^2=p^2c^2+m^2c^4$$
where
$$p\equiv\gamma m v$$
is the definition of momentum in special relativity. You can derive this formula using the definitions of energy and momentum in special relativity. From this formula, you can see that the energy of a massless particle is finite and proportional to its momentum.
Perhaps some of your confusion results from trying to use the nonrelativistic formulas for energy and momentum to understand the behavior of highly relativistic light.


text:
Q: Do moderators still indicate their interest before hats are turned on for their sites? The Winter Bash FAQ page includes the following question every year.

Why are you doing this to us?
For sites that have hats on by default, your moderator teams or your communities indicated that hats would be a fun, lighthearted thing to do. [ ... ]

I'm aware that moderators used to receive an email informing them on the duration of Winter Bash and that Winter Bash was held on a per-site opt-in basis (and there were actually sites that opted-out). 2016 appears to be the latest year I could find when such an email was sent out to moderators.
Do moderators still get a heads-up email informing them of the start of Winter Bash and for them to indicate their site's interest in Winter Bash? If not, is the FAQ page technically incorrect since all sites are now automatically opted-in to Winter Bash?

A: Nope - there's no email any longer on the sites I am a mod. In the past (aka the early days of Winterbash), some communities would post a Q/A on their meta, effectively asking "do we want to participate" and posting two answers (in short, "yes" and "no"), to give their members a chance to vote. Haven't seen this either in a while.
Conclusion:
As long as nobody actively lobbies to opt out, participating is the default. And for the individual user, they can always "bah, humbug" by clicking "No hats for me, please" and be done with it, without impeding those who love Winterbash. The others get to wear the SE equivalent of the Ugly Sweater or make a dash for the leaderboard.
I would assume that at some point the various mod teams have either opted in or not opted out, and we can take that as "valid until stated otherwise", so the FAQ is not necessarily incorrect, as the FAQ doesn't say "indicated for this season".


text:
Q: How to save Microsoft account password in Windows 8 Remote Desktop? With two Windows 8 PCs not on a domain, with a common Microsoft account present on each, it is easy to Remote Desktop between the two. The correct username is filled in for you; only the Microsoft account password is needed, which you can save.
The problem is that even if you save the password, it doesn't get used on later connections. A "Windows Security" dialog box appears, prompting "The credentials that were used to connect to Computer did not work. Please enter new credentials." At the bottom of the dialog is the error "The logon attempt failed".
The workaround is to reenter the password, but what is the solution to avoid the need to do so?

A: Make sure a HomeGroup isn't causing Windows credentials to be saved with Enterprise persistence.
Specifically, these steps resolved the problem:

*

*On each computer, leave the HomeGroup if on one.

*From the client computer, search Settings for "Manage Windows Credentials", and delete all credentials related to the other computer. (In particular, you may notice a credential TERMSRV/ComputerName that has Persistence set to enterprise.)

A: I'm not 100% sure about this solution since it was in Windows 7 but trying won't hurt.
The Local Group Policy Editor dialog box displays. In the tree in the left pane, navigate to the following item:
User Configuration | Administrative Templates | Windows Components | Remote Desktop Services
Select the Remote Desktop Connection Client item under Remote Desktop Services. In the Setting list on the right, double-click on the Do not allow passwords to be saved setting.

On the dialog box that displays, select the Disabled radio button.

Click OK to close the dialog box for the Do not allow passwords to be saved setting.

To close the Local Group Policy Editor dialog box, select Exit from the File menu.

Credits: HelpDeskGeek


text:
Q: How to address this instance of C4428 Visual C++ warning about a character literal? Currently Visual C++ issues C4428 warning

universal-character-name encountered in source

on the following code
const wchar_t someMagicValue = L'\ufffd';

I'd like to address this warning and I wonder whether the following:
const wchar_t someMagicValue = L'\xfffd';

will be fully equivalent code.
Will the latter code be fully equivalent to the former? What could be a better option?

A: As commented here
Compiler Warning (level 4) C4428 (VS2010)
this is most likely /just a bug/ in MSVC
See also this thread for a bit more discussion

A: Have you tried this?
const wchar_t someMagicValue = 0xfffd;


text:
Q: set typeface on SimpleAdapter Android @Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    pDialog.dismiss();

    if (status.equals("0")) {
        Toast.makeText(getApplicationContext(), "gagal menampilkan, restart app",
                Toast.LENGTH_SHORT).show();
    }

    ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
            dataList,
            R.layout.listitem,
            new String[] { "nama","alamat", "telp","latitude","longitude","jam","distance" },
            new int[] {R.id.nama, R.id.alamat, R.id.telp, R.id.lat, R.id.lon, R.id.jam, R.id.distance }
    );

    lve.setAdapter(adapter);

}

this activity is running with "list_view" layout, how to set typeface of the "list_item"? i need to do it in java, not in xml to force the typeface.
thanks in advance.


text:
Q: Android.Обновление LayoutManager при смене ориентации Имеется Activity c ViewPager. В одном из Page есть фрагмент с RecyclerView.
Там я задаю и LayoutManager и ScrollListener в методе onCreateView. Всё хорошо.
Поставил на активити android:configChanges="screenSize", для того чтобы активити не пересоздавалась при смене ориентации.
Так вот,как при смене ориентации снова вызывать LayoutManager и т.д, ?
К примеру, высчитались кол-во столбцов в GridAutofitLayoutManager ?
пробовал так:
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    Integer minWidth;
    minWidth = (int) getResources().getDimension(R.dimen.minItemWidht);
    Log.d("TAG ", String.valueOf(minWidth));

    layoutManager = new GridAutofitLayoutManager(context, minWidth);
     mRecyclerView.setLayoutManager(layoutManager);

}

Но не помогло. Во время дебага всё хорошо, GridAutofitLayoutManager высчитывает количество новых столбцов. Как только снимаешь точку остановку,перестаёт. Возможно времени не хватает?
Здесь код GridAutofitLayoutManager
totalSpice как-то иногда неправильно высчитывает

A: Помог мне
 mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    Integer minWidth;
                    minWidth = (int) getResources().getDimension(R.dimen.minItemWidht);
                    layoutManager = new GridAutofitLayoutManager(context, minWidth);
                    mRecyclerView.setHasFixedSize(true);
                    mRecyclerView.setLayoutManager(layoutManager);
                    adapterRecycler.notifyDataSetChanged();
                }
            });

A: Используй кастомный RecyclerView (public class AutofitRecyclerView extends RecyclerView)
А в нем в методе onMeasure можно пересчитывать количество.
Такой код работает хорошо:
package сom.example;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

public class AutofitRecyclerView extends RecyclerView {
    int spanCount = 1;
    private GridLayoutManager manager;
    private int columnWidth = -1;

    public AutofitRecyclerView(Context context) {
        super(context);
        init(context, null);
    }

    public AutofitRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public AutofitRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            int[] attrsArray = {
                    android.R.attr.columnWidth
            };
            TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
            columnWidth = array.getDimensionPixelSize(0, -1);
            array.recycle();
        }

        manager = new GridLayoutManager(getContext(), 5);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (getAdapter().getItemViewType(position)) {
                    case AppsAdapter.TYPE_HEADER:
                        return spanCount;
                    case AppsAdapter.TYPE_ITEM:
                        return 1;
                    default:
                        return 1;
                }
            }
        });
        setLayoutManager(manager);
    }

    @Override
    public GridLayoutManager getLayoutManager() {
        return manager;
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);
        if (columnWidth > 0) {
            spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
            manager.setSpanCount(spanCount);
        }
    }
}


text:
Q: Checkbox on change event is not working on Safari Thanks in advance for the help on this. I have a special requirement on my page where I needed a checkbox to "act" like a radio button, so only one can be checked at a time. To achieve that I used this snippet below"
<script>
$('input:checkbox').on('change', function() {
  $('input:checked').not($(this)).closest('.w-checkbox').click();
});
</script>

It works perfectly on Chrome. However, it doesn't work on Safari and allows more than one checkbox to be clicked. I was wondering if anyone had ideas on how to solve this because I have tried many alternatives and unfortunately need to have the checkbox

A: The proper way to uncheck a checkbox is by changing the checked property.

$('input:checkbox.w-checkbox').change(function() {
  $('input:checkbox.w-checkbox').not(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" class="w-checkbox" />
<input type="checkbox" class="w-checkbox" />
<input type="checkbox" class="w-checkbox" />


text:
Q: Lex/Flex :Regular expression for string literals in C/C++? I look here ANSI C grammar .
This page includes a lot of regular expressions in Lex/Flex for ANSI C.
Having a problem in understanding regular expression for string literals.
They have mentioned regular expression as \"(\\.|[^\\"])*\"
As I can understand \" this is used for double quotes, \\ is for escape character, . is for any character except escape character and * is for zero or more times.
[^\\"] implies characters except \ , " .
So, in my opinion, regular expression should be \"(\\.)*\".
Can you give some strings where above regular expression will fail?
or
Why they have used [^\\"]?

A: The regex \"(\\.)*\" that you proposed matches strings that consist of \ symbols alternating with any characters like:
"\z\x\p\r"

This regular expression would therefore fail to match a string like:
"hello"

The string "hello" would be matched by the regex \".*\" but that would also match the string """" or "\" both of which are invalid.
To get rid of these invalid matches we can use \"[^\\"]*\", but this will now fail to match a string like "\a\a\a" which is a valid string.
As we saw \"(\\.)*\" does match this string, so all we need to do is combine these two to get \"(\\.|[^\\"])*\".


text:
Q: python 3d list assign and index different result
When I assign to an element in 3d python list, it will change 3 element.
Does anyone know what happened?

A: Yep, It has to do with the underlying way in which arrays are stored in Python. When you created your array initially, with the [[0,0]]*4, you created four pointers to the same list(you did that four separate times, hence why 1/4 of your lists were changed). Thus, when you change 1 value, it changes it in that one list, but there are multiple pointers to the same list, so it appears to change multiple values. I highly recommend http://pythontutor.com/ for visualizing how your code is executed/the underlying structures at play.


text:
Q: XENServer hard disk crashed - Save my soul I am in the worst possible situation. Any help is like saving my soul and even more...
I had a machine on which Citrix Xen Server was installed and had three VMs and I was working on those machines with almost zero knowledge of XenServer.
Oneday I couldn't boot my machine and finally I had to recover my VMs. I made a couple of snapshots before the hard disk crashed but these were on the same machine :(
Now I took out the hard disk and connected it to a new machine with Windows XP using USB Sata connectors. I installed ubuntu on the machine and tried to browse the hard disk.
Now I want to know where are my VMs and snapshots. File ? Extension? Location?
How can I read the data in my VM. I am dying to recover one folder in any case which has 6 months of effort and I have to present that work in near future.
It's not just a tech question but my future depends upon it. Please help

A: Your best bet: Get a professional who really knows what he is doing have a look onto this.
Other than that, your first step must be to make an exact copy, bit by bit, of your disk in order to prevent doing more damage while you try to repair things. Get a second hard disk which is at least as big as the one you try to recover from.
From your description, I can't tell wether your hard drive is physically damaged or if you suffer from a logical problem, so I would recommend making the copy with ddrescue, which will continue to work even if it finds damaged sectors.
After that, I think XenServer uses LVM volumes for VM storage by default, but I am not sure so I won't make any more recommendations.

A: 1) What happend with your hard disk?
2) If you could some kind of way to clone your drive, do it
3) Working with Citrix XEn server not such hard as you think , all VMs located continiosly. It is important to know which File System was inside those Vm.s
4) I recommend to ask about your problem on hddguru.com forum . There a lot expert guys who working in data recovery field. They know much


text:
Q: how to pass a long String args from java app to bash script run spark subbmit? i i'm using a java app to pass arg to my spark submit bash script. instead of config all in spark-submit, I create a String contains all config of that job and pass it through the args, but it seem that spark can't understand it, what I did wrong?
CONF1=$1
CONF='--class "com.at.es_parent_child.SegmentIcebergEsV2" --master yarn --deploy-mode client --queue llap --num-executors 3 --driver-memory 1024m --executor-memory 1024m --executor-cores 4 --name [564889711]es_parent_child.[0].1668574353481 --conf "spark.executor.extraClassPath=/etc/hbase/conf" --conf "spark.driver.extraClassPath=/etc/hbase/conf" --conf "spark.serializer=org.apache.spark.serializer.KryoSerializer" --conf "spark.max.executor.failures=100" --conf "spark.rdd.compress=true" --conf "spark.sql.debug.maxToStringFields=2000" --conf "spark.sql.hive.convertMetastoreParquet=false" --conf "spark.default.parallelism=50" --conf "spark.debug.maxToStringFields=2000" --conf "hbase.defaults.for.version.skip=true" --conf "spark.yarn.executor.memoryOverhead=1024" --conf "spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkSessionCatalog" --conf "spark.sql.catalog.spark_catalog.type=hive" --conf "spark.sql.catalog.iceberg=org.apache.iceberg.spark.SparkCatalog" --conf "spark.sql.catalog.iceberg.type=hive" --conf "spark.sql.adaptive.coalescePartitions.enabled=true" --files "/etc/hbase/conf/hbase-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml"'
echo "--------------------------------------------"
echo $CONF
echo "--------------------------------------------"

sudo -u cdpcore /bin/sh /build/iceberg/spark-3.0.1-bin-hadoop2.7/bin/spark-submit $CONF --jars $(echo $JAR_LIB/*.jar | tr ' ' ',') $JAR_MAIN "$2" $3 $4 $5 &

#i use echo of this command and spark still run normal
echo sudo -u cdpcore /bin/sh /build/iceberg/spark-3.0.1-bin-hadoop2.7/bin/spark-submit $CONF --jars $(echo $JAR_LIB/*.jar | tr ' ' ',') $JAR_MAIN "$2" $3 $4 $5 &
~

the script above I pass $1 with a string like CONF, in my java value of CONF is
String CONF = "--class "com.at.es_parent_child.SegmentIcebergEsV2" --master yarn --deploy-mode client --queue llap --num-executors 3 --driver-memory 1024m --executor-memory 1024m --executor-cores 4 --name [564889711]es_parent_child.[0].1668574353481 --conf "spark.executor.extraClassPath=/etc/hbase/conf" --conf "spark.driver.extraClassPath=/etc/hbase/conf" --conf "spark.serializer=org.apache.spark.serializer.KryoSerializer" --conf "spark.max.executor.failures=100" --conf "spark.rdd.compress=true" --conf "spark.sql.debug.maxToStringFields=2000" --conf "spark.sql.hive.convertMetastoreParquet=false" --conf "spark.default.parallelism=50" --conf "spark.debug.maxToStringFields=2000" --conf "hbase.defaults.for.version.skip=true" --conf "spark.yarn.executor.memoryOverhead=1024" --conf "spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkSessionCatalog" --conf "spark.sql.catalog.spark_catalog.type=hive" --conf "spark.sql.catalog.iceberg=org.apache.iceberg.spark.SparkCatalog" --conf "spark.sql.catalog.iceberg.type=hive" --conf "spark.sql.adaptive.coalescePartitions.enabled=true" --files "/etc/hbase/conf/hbase-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml"
"

#and I use

String[] cmd = {"/bin/sh", System.getProperty("user.dir") + "/spark_job.sh", CONF,
                            zKUrl,""+ task.getPortalId(), task.getJobId(),""+ task.getIndexCode()};

the error is
22/11/16 12:40:01 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Error: Failed to load class "com.at.es_parent_child.SegmentIcebergEsV2".

how can i fix this issue?
Thanks and best regards

A: Try the following in your bash script. The value at line 10 might need to be enclosed in singles quotes owing to the square brackets. When $CONF is used it must be used as "$CONF"
CONF=$(cat << EOF
--class com.at.es_parent_child.SegmentIcebergEsV2 \
--master yarn \
--deploy-mode client \
--queue llap \
--num-executors 3 \
--driver-memory 1024m \
--executor-memory 1024m \
--executor-cores 4 \
--name [564889711]es_parent_child.[0].1668574353481 \
--conf spark.executor.extraClassPath=/etc/hbase/conf \
--conf spark.driver.extraClassPath=/etc/hbase/conf \
--conf spark.serializer=org.apache.spark.serializer.KryoSerializer \
--conf spark.max.executor.failures=100 \
--conf spark.rdd.compress=true \
--conf spark.sql.debug.maxToStringFields=2000 \
--conf spark.sql.hive.convertMetastoreParquet=false \
--conf spark.default.parallelism=50 \
--conf spark.debug.maxToStringFields=2000 \
--conf hbase.defaults.for.version.skip=true \
--conf spark.yarn.executor.memoryOverhead=1024 \
--conf spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkSessionCatalog \
--conf spark.sql.catalog.spark_catalog.type=hive \
--conf spark.sql.catalog.iceberg=org.apache.iceberg.spark.SparkCatalog \
--conf spark.sql.catalog.iceberg.type=hive \
--conf spark.sql.adaptive.coalescePartitions.enabled=true \
--files /etc/hbase/conf/hbase-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml
EOF
)


text:
Q: Making specific author bold using biblatex I'm trying to implement the example of this answer poster by Audrey as follows:
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}
\usepackage{xpatch}% or use http://tex.stackexchange.com/a/40705

\usepackage[style=authoryear, sorting=ynt, backend=biber, maxbibnames=99]{biblatex}
\begin{filecontents}{\jobname.bib}
@MISC{test1,
  AUTHOR    = {Last1, First1 and Last2, First2 and Last3, First3},
}
@MISC{test2,
  AUTHOR    = {Last2, First2 and Last3, First3 and Last1, First1},
}
\end{filecontents}

\addbibresource{\jobname.bib}
%\addbibresource{publications.bib}

\setlength\bibitemsep{1.5\itemsep}

\newbibmacro*{name:bold}[2]{%
  \edef\blx@tmp@name{\expandonce#1, \expandonce#2}%
  \def\do##1{\ifdefstring{\blx@tmp@name}{##1}{\bfseries\listbreak}{}}%
  \dolistloop{\boldnames}}
\newcommand*{\boldnames}{}
\makeatother

\xpretobibmacro{name:family}{\begingroup\usebibmacro{name:bold}{#1}{#2}}{}{}
\xpretobibmacro{name:given-family}{\begingroup\usebibmacro{name:bold}{#1}{#2}}{}{}
\xpretobibmacro{name:family-given}{\begingroup\usebibmacro{name:bold}{#1}{#2}}{}{}
\xpretobibmacro{name:delim}{\begingroup\normalfont}{}{}

\xapptobibmacro{name:family}{\endgroup}{}{}
\xapptobibmacro{name:given-family}{\endgroup}{}{}
\xapptobibmacro{name:family-given}{\endgroup}{}{}
\xapptobibmacro{name:delim}{\endgroup}{}{}

% just for demonstration
\ExecuteBibliographyOptions{maxnames=99,giveninits}
\DeclareNameAlias{default}{family-given/given-family}

\begin{document}
\nocite{*}

\renewcommand*{\boldnames}{}
\forcsvlist{\listadd\boldnames}
{{Last2, First2} }
\printbibliography[heading=none]
\end{document}

However the name of the author does not appear in bold in the pdf output.
What am I doing wrong?
EDIT
I tried the answer given by @moewe  but get the following error message
LaTeX Warning: File `try9.bib' already exists on the system.
               Not generating it from this source.

(/usr/local/texlive/2019/texmf-dist/tex/latex/biblatex/lbx/british.lbx
(/usr/local/texlive/2019/texmf-dist/tex/latex/biblatex/lbx/english.lbx))

Package biblatex Warning: Conflicting options.
(biblatex)                '<namepart>inits' conflicts with 'uniquename=full'.
(biblatex)                Setting 'uniquename=init' on input line 81.

(./try9.aux)
No file try9.bbl.

LaTeX Warning: Citation 'nhblx@name@1' on page 1 undefined on input line 84.

LaTeX Warning: Empty bibliography on input line 85.

(./try9.aux)

LaTeX Warning: There were undefined references.

Package biblatex Warning: Please (re)run Biber on the file:
(biblatex)                try9
(biblatex)                and rerun LaTeX afterwards.

 )
No pages of output.
Transcript written on try9.log.

EDIT 2
I edited the line as follows:
\usepackage[style=authoryear, sorting=ynt, backend=biber, maxbibnames=99, uniquename=init]{biblatex}

ran biber try9 and then pdflatex try9 (where try9.tex is the name of the file) but got the following error message
LaTeX Warning: File `try9.bib' already exists on the system.
               Not generating it from this source.

(/usr/local/texlive/2019/texmf-dist/tex/latex/biblatex/lbx/british.lbx
(/usr/local/texlive/2019/texmf-dist/tex/latex/biblatex/lbx/english.lbx))
(./try9.aux) (./try9.bbl)

! LaTeX Error: Command \mkbibcompletename undefined.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.84 \addboldnames{{Last2, First2}}

?

! LaTeX Error: Command \mkbibcompletename undefined.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.85 \printbibliography[heading=none]

?

! LaTeX Error: Command \mkbibcompletename undefined.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.85 \printbibliography[heading=none]

?
[1{/usr/local/texlive/2019/texmf-var/fonts/map/pdftex/updmap/pdftex.map}]
(./try9.aux) ){/usr/local/texlive/2019/texmf-dist/fonts/enc/dvips/cm-super/cm-s
uper-t1.enc}</usr/local/texlive/2019/texmf-dist/fonts/type1/public/cm-super/sfr
m1000.pfb>
Output written on try9.pdf (1 page, 12913 bytes).
Transcript written on try9.log.

A: There are two issues here.

*

*The code is missing \makeatletter before the definition of name:bold. It should be
\makeatletter
\newbibmacro*{name:bold}[2]{%
  \edef\blx@tmp@name{\expandonce#1, \expandonce#2}%
  \def\do##1{\ifdefstring{\blx@tmp@name}{##1}{\bfseries\listbreak}{}}%
  \dolistloop{\boldnames}}
\newcommand*{\boldnames}{}
\makeatother

*This method of comparing names is string-based. That means that you must give the name you want to highlight in the same format as in the output. Since the code forces given name initials with giveninits, you also need to use the initials form. Note that . is replaced by \bibinitperiod. You need to take that into account when you fill \boldnames.
\forcsvlist{\listadd\boldnames}{{Last2, F\bibinitperiod}}

It will come as no surprise that I'll take this opportunity to plug my answer to Make specific author bold using biblatex. That answer uses a hash-based approach to compare names, which is generally much more reliable and stable than the string-based approach. The code is a bit longer, because we need a way to have Biber generate the hashes for us.
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}
\usepackage[style=authoryear, sorting=ynt, backend=biber, maxbibnames=99]{biblatex}

\makeatletter
\def\nhblx@bibfile@name{\jobname -nhblx.bib}
\newwrite\nhblx@bibfile
\immediate\openout\nhblx@bibfile=\nhblx@bibfile@name

\immediate\write\nhblx@bibfile{%
  @comment{Auto-generated file}\blx@nl}

\newcounter{nhblx@name}
\setcounter{nhblx@name}{0}

\newcommand*{\nhblx@writenametobib}[1]{%
  \stepcounter{nhblx@name}%
  \edef\nhblx@tmp@nocite{%
    \noexpand\AfterPreamble{%
      \noexpand\setbox0\noexpand\vbox{%
        \noexpand\nhblx@getmethehash{nhblx@name@\the\value{nhblx@name}}}}%
  }%
  \nhblx@tmp@nocite
  \immediate\write\nhblx@bibfile{%
    @misc{nhblx@name@\the\value{nhblx@name}, author = {\unexpanded{#1}}, %
          options = {dataonly=true},}%
  }%
}

\AtEndDocument{%
  \closeout\nhblx@bibfile}

\addbibresource{\nhblx@bibfile@name}

\newcommand*{\nhblx@boldhashes}{}
\DeclareNameFormat{nhblx@hashextract}{%
  \xifinlist{\thefield{hash}}{\nhblx@boldhashes}
    {}
    {\listxadd{\nhblx@boldhashes}{\thefield{hash}}}}

\DeclareCiteCommand{\nhblx@getmethehash}
  {}
  {\printnames[nhblx@hashextract][1-999]{author}}
  {}
  {}

\newcommand*{\addboldnames}{\forcsvlist\nhblx@writenametobib}
\newcommand*{\resetboldnames}{\def\nhblx@boldhashes{}}

\newcommand*{\mkboldifhashinlist}[1]{%
  \xifinlist{\thefield{hash}}{\nhblx@boldhashes}
    {\mkbibbold{#1}}
    {#1}}
\makeatother

\DeclareNameWrapperFormat{boldifhashinlist}{%
  \renewcommand*{\mkbibcompletename}{\mkboldifhashinlist}%
  #1}

\DeclareNameWrapperAlias{sortname}{default}
\DeclareNameWrapperAlias{default}{boldifhashinlist}

% just for demonstration
\ExecuteBibliographyOptions{maxnames=99,giveninits}
\DeclareNameAlias{default}{family-given/given-family}
\setlength\bibitemsep{1.5\itemsep}

\begin{filecontents}{\jobname.bib}
@MISC{test1,
  AUTHOR    = {Last1, First1 and Last2, First2 and Last3, First3},
}
@MISC{test2,
  AUTHOR    = {Last2, First2 and Last3, First3 and Last1, First1},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\nocite{*}

\addboldnames{{Last2, First2}}
\printbibliography[heading=none]
\end{document}


text:
Q: How to change the style with props How to change the style in React Native?
I need to change the color of the text when it is true or false
here is my code:
Styles Area
LIVE:{
        color: "red"
    },
    Comp: {
        color: "green"
},

Main
<Text style={MyCardStyle.AnyText}>{isLive == false ? /* MyCardStyle.Comp */ : /* MyCardStyle.LIVE */ }</Text>
// The commented out codes have error as "Objects are not valid as a React child"

Props
<MyMatchCard
    isLive={true}
    />

Here i want to change the color of the Text to green when its false or red when its true
How to actually apply the color without getting an error?

A: One way to do it is to change the style object to function instead. That function will take a parameter that will be used to define the text color:
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants'

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

const MyText = ({isLive}) => {
  return (
      <Text style={styles.text(isLive)}>
        Change code in the editor and watch it change on your phone! Save to get a shareable url.
      </Text>
  )
}
export default function App() {
  return (
    <View style={styles.container}>
      <MyText isLive />
      <MyText />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  text: (isLive) => ({
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: isLive ? 'green' : 'black'
  }),
});

A: You can also pass the condition to the style prop
const MyText = ({isLive}) => {
  return (
      <Text style={{color: isLive? 'green' : 'red' }}>
        Your text
      </Text>
  )
}


text: Q: GetClassName[] in c++ returns SWT_Window0 on mousehover on IE I am writing a code to get the class name of internet explorer when mouse hovers over IE. I have used WindowFromPoint() to get the current window below the cursor and have passed the retrieved window in the GetClassName(). When i print the class name i get the value as SWT_Window0 instaed of INTERNET EXPLORER_SERVER. Please tell me the solution to solve this issue


text:
Q: Build Errors Intel C++ (Knights Corner) ipo: warning #11010: file format not recognized I am trying to write a code to be build on 3 systems which mainly differentiate on the basis of their Register Lengths:

*

*SSE (128 Bits)

*AVX (256 Bits)

*MIC (Intel's Knights Corner 512 Bits)

My Makefile builds the executable depending on the system of choice, which can be chosen from config.mk which looks like:
MIC=0           # 0 = no MIC kernels        | 1 = build MIC kernels
AVX=0           # 0 = no AVX kernels        | 1 = build AVX kernels
SSE=0           # 0 = no SSE kernels        | 1 = build SSE kernels

My Main Makefile is:
#   CONFIGURE BUILD SYSTEM
include config.mk
CXXFLAGS = -O2 -g -pedantic -Wextra -Wno-format -Wall

ifeq '$(strip $(SSE))' '1'
    CXXFLAGS += -msse4.2
    TAG = LIMA
    #@echo "$(CXXFLAGS)"
endif

ifeq '$(strip $(AVX))' '1'
    CXXFLAGS += -mavx
    TAG = SANDY
    #@echo "$(CXXFLAGS)"
endif

ifeq '$(strip $(MIC))' '1'
    CXXFLAGS += -mmic
    TAG = MIC
    #@echo "$(CXXFLAGS)"
endif

CC       = icc
CXX      = icpc
INCLUDES = -I./src/includes
CXXFLAGS := $(CXXFLAGS) $(DEFINES) $(INCLUDES)
DEFINES  = -D_GNU_SOURCE -DDEBUG
LINKER   = $(CXX) -liomp5 -lpthread
LIBS     =
LFLAGS   =

#   BUILD PARAMETERS
TARGET     = SpMvM_$(TAG)
SRC_DIR    = ./src
MAKE_DIR   = ./
Q         ?= @
BUILD_DIR  = ./$(TAG)

VPATH = $(SRC_DIR)
OBJ = $(addprefix $(BUILD_DIR)/,$(notdir $(patsubst %.cpp,%.o, $(wildcard $(SRC_DIR)/*.cpp)) ))

${TARGET}: $(BUILD_DIR) $(OBJ)
    @echo "===>  LINKING  $(TARGET)"
    @echo "$(Q)${LINKER} ${LFLAGS} -o $(TARGET) $(OBJ) $(LIBS)"
    $(Q)${LINKER} ${LFLAGS} -o $(TARGET) $(OBJ) $(LIBS)

$(BUILD_DIR)/%.o:  %.cpp
    @echo "===>  COMPILE  $@"
    @echo "$(Q)$(CXX) $(CXXFLAGS) -c $< -o $@"
    $(Q)$(CXX) $(CXXFLAGS) -c $< -o $@

$(BUILD_DIR):
    @mkdir $(BUILD_DIR)

.PHONY: clean distclean

clean:
    @echo "===>  CLEAN"
    @rm -rf $(BUILD_DIR)
    @rm -f tags
    @rm -f $(TARGET)
    @rm -f *~

distclean: clean
    @echo "===> DIST CLEAN"
    @rm -f $(TARGET)
    @rm -f tags

clean_dir:
    @echo "===> CLEAN DIR"
    @rm -rf LIMA/ SANDY/ MIC/

clean_all:
    @echo "===> CLEAN ALL"
    @rm -f  SpMvM_LIMA SpMvM_SANDY
    @rm -rf LIMA/ SANDY/ MIC/

The config.mk helps in choosing the right compiler flags (-msse4.2, -mavx, -mmic).
The test code is a simple "HELLO WORLD" application in c++. It works with no errors on SSE and AVX systems.
When I tried to compile on MIC, the following error shows up:
===>  COMPILE  MIC/main.o
@icpc -O2 -g -pedantic -Wextra -Wno-format -Wall -openmp -mmic  -I./src/includes -c ./src/main.cpp  -o MIC/main.o
===>  LINKING  SpMvM_MIC
@icpc -liomp5 -lpthread -o SpMvM_MIC ./MIC/main.o
ipo: warning #11010: file format not recognized for ./MIC/main.o
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
ld: ./MIC/main.o: Relocations in generic ELF (EM: 181)
./MIC/main.o: could not read symbols: File in wrong format
make: *** [SpMvM_MIC] Error 1

I have searched enough to understand that ipo errors have something to do with compiling and linking on different system. But it doesn't make sense in my case. The executable (SpMvM_$(TAG)) and Objects files ($(BUILD_DIR)/) are created on each system and they are all named with a suffice ($(TAG) = LIMA, SANDY, MIC) depending on the system to be used. As a result on object file from one system overlaps in linking or usage to the other.
Can someone Please let me know with what is wrong?


text:
Q: Android Camera.Parameters setPictureSize not working I am trying to set the best possible output picture size in my camera object. So that, i can get a perfect downscaled sample image and display it.
During debugging i observed i am setting output picture size exactly the size of my screen dimensions. But when i DecodeBounds of the returned image by camera. I get some larger number!
Also i am not setting my display dimensions as expected output picture size. Code used to calculate and set the output picture size is given below.
I am using this code for devices having API level < 21, so using camera shouldn't be a problem.
I don't have any idea of why i am getting this behavior. Thanks in advance for help!
Defining Camera parameter
Camera.Parameters parameters = mCamera.getParameters();
setOutputPictureSize(parameters.getSupportedPictureSizes(), parameters); //update paramters in this function.

//set the modified parameters back to mCamera
mCamera.setParameters(parameters);

Optimal picture size calculation
private void setOutputPictureSize(List<Camera.Size> availablePicSize, Camera.Parameters parameters)
{
    if (availablePicSize != null) {

        int bestScore = (1<<30); //set an impossible value.
        Camera.Size bestPictureSize = null;

        for (Camera.Size pictureSize : availablePicSize) {

            int curScore = calcOutputScore(pictureSize); //calculate sore of the current picture size
            if (curScore < bestScore) { //update best picture size
                bestScore = curScore;
                bestPictureSize = pictureSize;
            }
        }
        if (bestPictureSize != null) {
            parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
        }
    }
}

//calculates score of a target picture size compared to screen dimensions.
//scores are non-negative where 0 is the best score.
private int calcOutputScore(Camera.Size pictureSize)
{
    Point displaySize = AppData.getDiaplaySize();
    int score = (1<<30);//set an impossible value.

    if (pictureSize.height < displaySize.x || pictureSize.width < displaySize.y) {
        return score;  //return the worst possible score.
    }

    for (int i = 1; ; ++i) {

        if (displaySize.x * i > pictureSize.height || displaySize.y * i > pictureSize.width) {
            break;
        }
        score = Math.min(score, Math.max(pictureSize.height-displaySize.x*i, pictureSize.width-displaySize.y*i));
    }
    return score;
}

A: Finally i resolved the issue after many attempts!  Below are my findings:
Step 1. If we are already previewing, call mCamera.stopPreview()
Step 2. Set modified parameters by calling mCamera.setParameters(...)
Step 3. Start previewing again, call mCamera.startPreview()
If i call mCamera.setParameters without stopping preview (Assuming camera is previewing). Camera seems to ignore the updated parameters.
I came up with this solution after several trail and errors. Anyone know better way to update parameters during preview please share.


text:
Q: Return all joined rows in SQL So I am messing around with wordpress and trying to get all the rows a row joins to. For now, I can only seem to get one row it joins to. I know there has to be some element of GROUP BY, but I just can't seem to figure it out.
SELECT posts.*, meta.meta_value
                FROM wp_g6exrf_posts as posts
                LEFT OUTER JOIN wp_g6exrf_postmeta as meta
                ON meta.post_id = posts.ID
                WHERE ! ( posts.post_status = 'auto-draft' )
                GROUP BY meta.post_id

So I am joining to the meta table and expecting more than one column to meet the join condition.
Sincere thanks for any help. It is greatly appreciated.

A: postmeta makes very little sense without seeing meta_key.
GROUP BY doesn't make sense unless you're doing some kind of aggregate. It's crushing your multiple rows for each post into one, and returning just one of your meta_value items, a randomly chosen one.
Try this:
SELECT posts.*,
       meta.meta_key, meta.meta_value
  FROM wp_g6exrf_posts as posts
  LEFT OUTER JOIN wp_g6exrf_postmeta as meta ON meta.post_id = posts.ID
 WHERE ! ( posts.post_status = 'auto-draft' )
 ORDER BY posts.id, meta.meta_key, meta.meta_value


text:
Q: Continuous Release succeeded but website didn't change I successfully set up a CI/CR process for my ASP.NET website to Azure web app service. I did some changes, queued up a new build and waited for both the build and release to succeed. However, when I launch the website, I didn't see my changes.
The release definition is like this:

The Azure web app service is like this:

I can see that the release is successful on vsts.

I can see that the release is successful on Azure.

But I can't see my changes on the website. I can see the changes if I run the website locally from my Visual Studio. I am pretty sure I checked in all my changes to vsts. Did I miss some steps here?
--Updates------------------------------------
This time I checked the "Publish using Web Deploy" option like this:

But still no luck. :(
You can find the Release log files here

A: If you are getting any error message when trying to access the website, share the detailed error message, which might help to resolve the issue.
Also, try to add "MSDEPLOY_RENAME_LOCKED_FILES = 1" in "Application Settings" tab for your web app and see if it helps. You may refer the below screenshot,

Reference: https://learn.microsoft.com/en-us/vsts/build-release/apps/cd/deploy-webdeploy-webapps?view=vsts.

A: You specified the zip file in Package or folder input box, but don't check Publish using Web Deploy option, so it just upload the zip file to web service, that's the reason.
You need to check Publish using Web Deploy option if deploying with the zip file.
Update:
Refer to these steps below to publish web app:

*

*Specify MSBuild Arguments in Visual Studio Build task: /p:SkipInvalidConfigurations=true /p:DeployOnBuild=true /p:WebPublishMethod=FileSystem /p:publishUrl="$(build.artifactstagingdirectory)\\" /p:DeployDefaultTarget=WebPublish

*Archive Files task (Root folder or file to archive: $(Build.artifactstagingdirectory))

*Publish Build Artifacts


text:
Q: Determine Logic for MySQL Select - Reservation System I'm creating an equipment reservation (PHP/MySQL) for my school.
My database looks like this:
tblEvents:
 id
 start
 end
 equipID

tblEquipment:
  id
  name
  description

I'd like to know the best way to query the database based on a user's time parameters to see if a certain item is 'not available.'
For example, if I have the following data:
tblEvents:
  id      start          end         equipID
  1     1251312300    1251324000       1

And the user submits the query, looking to see if "equipID" 1 is available, and they put:
1251300300 as their start and 1251524000 as their end.
Any help on getting this started would be great.  Thanks.

A: I'm not 100% sure on this, but I think this query should be pretty close:
select * from tblEvents
where (@starttime >= start && @starttime <= end) /* Starts while someone else has it */
or (@endtime >= start && @endtime <= end) /* Ends while someone else has it */
or (@startime <= start && @endtime >= end) /* Starts before & ends after someone else has it*/
and equipID = @equipID

Replace @starttime, @endtime & @equipID with the appropriate equipment id and start & end times entered by the user.  If this query returns no results, then there should be no time conflicts.
Basicly it's checking for these 3 scenarios, where the * is your start & end time, the - is unused time, and the | is time its being used by someone else:
-|||||*|||||------*------
------*--------|||*||||--
------*--|||||||--*------

A: SELECT * FROM tblEvents
WHERE NOW() > FROM_UNIXTIME(end)


text:
Q: How can I return this object read in from a file? So what I am trying to do here is load a Customer object in from a file but I don't know how to return the object in the method. As the code stands now I get an error saying return type incompatible java.lang.object found needs Customer.
public static Customer loadCustomer(String customerNum) {
    try {
        String fileName = customerNum + ".txt";
        InputStream file = new FileInputStream(fileName);
        InputStream buffer = new BufferedInputStream(file);
        ObjectInput input = new ObjectInputStream(buffer);
        Object x = input.readObject();
        return x;
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

I was thinking I could do something like this but it doesn't work either.
public static Customer loadCustomer(String customerNum) {
    try {
        String fileName = customerNum + ".txt";
        InputStream file = new FileInputStream(fileName);
        InputStream buffer = new BufferedInputStream(file);
        ObjectInput input = new ObjectInputStream(buffer);
        Object x = input.readObject();
        Customer y = new Customer(x);
        return y;
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

//or do something like this:Customer x = new Customer(input.readObject)

Im still in the java learning process so if you see any other errors please let me know. As always I appreciate everyones time for helping me out with this, looking forward to the day when I have the knowledge to pay it forward and help others.

A: Try replacing Object x = input.readObject(); with Customer x = (Customer) input.readObject();


text:
Q: Using function to change color based on Boolean value in another function in JS I have a function that returns something like this :
let checkAddedValuesFunction =

{"444" => Array(1), "T" => Array(1), ":778" => Array(1)}

0: {"444" => Array(1)}
key: "444"
  value: Array(1)
  0: {isValue: true, string: "111:222:444", at: 8}

1: {"T" => Array(1)}
key: "T"
 value: Array(1)
 0: {isValue: false, string: "SQL_DT", at: 5}

2: {":778" => Array(1)}

I'm trying to create a function that will change color of the elements in the string based on isValue true/false statement. I'm currently doing something like this but it seems to be not working at all:

    const changeColor = (target) => {
      for (const [key, value] of Object.entries(checkAddedValuesFunction)) {

        ~~// FIND IF VALUE IS TRUE THEN GO AND CHANGE COLOR //~~

        if (document.querySelector(".compareKey")) {
          document.querySelector(".compareKey").style.backgroundColor = "red";
        } else if (document.getElementsByClassName(".compareValue")) {
          document.getElementsByClassName(".compareValue").style.backgroundColor =
            "red";
        }
      }

    };

A: There are many little mistakes in your code:

*

*.querySelector() returns only the first matching item, you should use .querySelectorAll()

*You cannot access the .style property of a nodelist, you have to loop the nodelist and access each node individually

*.getElementsByClassName() take the class name as argument, so without the .
Here is a small reduced example:

function changeElementsBgColor(elements, color) {
  for(let i=0; i<elements.length; i++) {
    elements[i].style.backgroundColor = color;
  }
}

if (document.querySelector(".compareKey")) {
  const elements = document.querySelectorAll(".compareKey")
  changeElementsBgColor(elements, "red");
}

if (document.getElementsByClassName("compareValue")) {
  const elements = document.getElementsByClassName("compareValue");    changeElementsBgColor(elements, "red");
}

compareKey element 1

compareKey element 2

compareValue element 1

compareValue element 2


text:
Q: Nombres de variables con identificadores de otras variables Viendo el tutorial de C de tutorialspoint me encontré el siguiente ejemplo:
#include <stdio.h>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void) {
   int token34 = 40;
   tokenpaster(34);
   return 0;
}

Y entonces me pregunté: ¿Y porque no creo variables cuyos nombres sean valores de otras variables?
La pregunta no se entiende muy bien, pero mi intento por responderla si:
#include <stdio.h>

int main()
{
    for(int contador = 0; contador < 10; contador++)
    {
        variable##contador = contador;
    }

    for(contador = 0; contador < 10; contador++)
    {
        printf("%d\n", variable##contador);
    }

    return 0;
}

Ese código no compila bien, pero sé que debe haber una forma de lograr mi objetivo...

A: #define tokenpaster(n) printf ("token" #n " = %d", token##n)

Esto es una macro, la macro recibe un único parámetro n y con ese parámetro genera la siguiente línea de código:
printf("token" #n " = %d", token##n)

Donde:

*

*#n convierte a string el valor asignado a n

*##n concatena el valor de n con la palabra token.

Así, en el ejemplo que te ponen:
tokenpaster(34);

Se genera la siguiente línea de código:
printf("token34 = %d", token34)

Dicho esto, las almohadillas no forman parte del lenguaje C. No las puedes usar en código C. El único que las interpreta es el precompilador. Esto plantea ciertas limitaciones. Efectivamente, dado que el precompilador se ejecuta antes que el compilador, el código del precompilador no se ve afectado por el código C++ (bucles, valor de las variables, ...).
De hecho, el ejemplo anterior fallaría si a la macro le pasases una variable:
tokenpaster(token34);

En este caso el código que generaría la macro sería el siguiente:
printf("tokentoken34 = %d", tokentoken34);

Ante esta entrada, el compilador generaría un error, ya que no sería capaz de encontrar la variable tokentoken34.
Lo lamento pero esta vía no te va a permitir conseguir tus objetivos.
Para conseguir lo que pretendes deberías implementar una función a la que le pudieses pasar variables junto con su identificador. Esta función debería recorrer el string y reemplazar los identificadores que vaya encontrando por los valores que correspondan.
Para hacer esta tarea tienes que entender cómo funcionan las funciones variádicas en C. No me voy a extender en este tema, hay bastante documentación en Internet.
Un posible y limitado ejemplo (únicamente trabaja con enteros) de cómo podría quedar la función:
void print(char const* string, int count, ...)
{
    struct data
    {
        char name[100];
        int value;
    };

    int totalArgs = count;
    count*=2;

    va_list args;
    va_start(args, count);

    struct data * parameters = (struct data*)malloc(totalArgs*sizeof(struct data));
    for( int i=0; i<totalArgs; i++)
    {
        strcpy(parameters[i].name, va_arg(args, char*));
        parameters[i].value = va_arg(args, int);
    }

    va_end(args);

    for( int i=0; string[i]!='\0'; ++i )
    {
        if( string[i] == '{' )
        {
            int replaced = 0;
            int j;
            for( j=i+1; string[j]!='}'; ++j );

            for( int dataIndex=0; dataIndex<totalArgs; ++dataIndex )
            {
                if( memcmp(string+i+1, parameters[dataIndex].name, j-i-1) == 0 )
                {
                    printf("%d", parameters[dataIndex].value);
                    i=j;
                    replaced = 1;
                    break;
                }
            }

            if( !replaced )
            {
                while(i<=j)
                {
                    putchar(string[i++]);
                }
                i--;
            }
        }
        else
        {
            putchar(string[i]);
        }
    }

    free(parameters);
}

Para usarla hay que facilitarle una lista con los diferentes identificadores y sus valores de reemplazo:
int main()
{
    int value = 123;
    print("X={X} value={value} other={other}", 2, "X", 44, "value", value);
}

Puedes verlo funcionando aquí


text:
Q: What is Sqlite used for? I don't know how authoritative this is but I found this:
http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations
and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?
Thank you.
EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:
Under appropriate uses for sqlite it has:
Situations Where SQLite Works Well
•Websites
SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.
Situations Where Another RDBMS May Work Better
•Client/Server Applications
If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.
A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.
The Question:
I'm going to show my ignorance here but what is the difference between these two?

A: It's often used for embedded applications.
It can be very handy to use a database like storage when you have no access to a database service. So SQLite is used since it's just a file you store somewhere.

A: I also find that using SQLite is good for getting a prototype application together pretty quickly without the overhead of having a seperate DB server or bogging a development environment with an instance of MySQL/Oracle/Whatever.
Also easy to pick up and move the database to a different machine if you need to.

A: The iPhone uses it for call history, SMS messages, contacts, and other type of data.  Like Ólafur Waage said, good for embedded applications on mobile device because it's lightweight.  I have used it also on stand alone applications.  Easy to use and available on most platforms.

A: This is answered well by sqlite itself : Appropriate use of sqlite
Another way to look at SQLite is this:
SQLite is not designed to replace Oracle. It is designed to replace fopen().

A: It's good for situations where you don't have access to a "real" database and still want the power of a relational db. For example, Firefox stores a bunch of information about your settings/history/etc in an SQLite database. You can't expect everyone that runs firefox to have MySQL or postgre installed on their machine.
It's also perfectly capable of running relatively-low traffic, read-heavy websites. The performance of it is overall very good, it's more than the large majority of websites need for their traffic levels.

A: Think about simple client or desktop apps that could make use of a db, like as a poor example, an address book. Rather than bundling a huge db engine like mysql or postgre with your deliverable, sqlite is very lightweight and easy to include with your finished app.

A: This FLOSS Weekly podcast episode talks with the creator of SQLite and covers among other things goes over the type of things you would use it for.  Everything from file systems for mobile phones to smallish web sites.

A: In the simplest terms, SQLite is a public-domain software package that provides a
relational database management system, or RDBMS. Relational database systems are
used to store user-defined records in large tables. In addition to data storage and management,
a database engine can process complex query commands that combine data
from multiple tables to generate reports and data summaries. Other popular RDBMS
products include Oracle Database, IBM's DB2, and Microsoft's SQL Server on the
commercial side, with MySQL and PostgreSQL being popular open source products.
The "Lite" in SQLite does not refer to its capabilities. Rather, SQLite is lightweight
when it comes to setup complexity, administrative overhead, and resource usage.
For detail info and solution about SQLite visit the link below:
http://blog.developeronhire.com/what-is-sqlite-sqlite/
Thank you.

A: What the above two answers say. Expanding slightly on Chad Birch's answer, its teh calls to the SQLite db, and a rather poor implementation of sync() that causes FF3 to be so slow in linux.


text:
Q: Как закруглить при анимации углы иконки гамбургера Есть такой пример:

document.querySelector('#svg').addEventListener('click', function() {
  [...document.querySelectorAll('.line')].forEach(s => {
    s.classList.contains('path-line') ?
      s.classList.remove('path-line') :
      s.classList.add('path-line');
  })
})
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
body {
  background-color: #272727;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

svg {
  background-color: black;
}

#path_line_3 {
  stroke-dasharray: 30 43;
  stroke-dashoffset: 0;
  transition: all .2s;
}

#path_line_1 {
  stroke-dasharray: 30 43;
  stroke-dashoffset: 0;
  transition: all .2s;
}

#path_line_2 {
  stroke-dasharray: 30 43;
  stroke-dashoffset: 0;
  transition: all .2s;
}

#path_line_2.path-line {
  stroke-dasharray: 0 30;
  stroke-dashoffset: 0;
}

#path_line_3.path-line {
  stroke-dasharray: 43.4 30;
  stroke-dashoffset: -30;
}

#path_line_1.path-line {
  stroke-dasharray: 43.4 30;
  stroke-dashoffset: -30;
}
<svg id="svg" version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 50 50">
        <path id="path_line_1" class="line" d="M 10 10, 40 10, 10 40" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" />

        <path id="path_line_2" class="line" d="M 25 25, 40 25" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" />

        <path id="path_line_3" class="line" d="M 10 40, 40 40, 10 10" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3" />

    </svg>

Можно ли закруглить острые углы, отмеченные на картинке ниже.

A: Не сразу понял что нужно кликнуть.
За оформление соединения сегментов линий в SVG отвечает свойство stroke-linejoin оно может принимать такие-же значения как и stroke-linecap, который Вы уже использовали:
bevel | miter | round

Вам поможет  stroke-linejoin="round"

document.querySelector('#svg').addEventListener('click', function() {
  [...document.querySelectorAll('.line')].forEach(s => {
    s.classList.contains('path-line') ?
      s.classList.remove('path-line') :
      s.classList.add('path-line');
  })
})
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
body {
  background-color: #272727;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

svg {
  background-color: black;
}

#path_line_3 {
  stroke-dasharray: 30 43;
  stroke-dashoffset: 0;
  transition: all .2s;
}

#path_line_1 {
  stroke-dasharray: 30 43;
  stroke-dashoffset: 0;
  transition: all .2s;
}

#path_line_2 {
  stroke-dasharray: 30 43;
  stroke-dashoffset: 0;
  transition: all .2s;
}

#path_line_2.path-line {
  stroke-dasharray: 0 30;
  stroke-dashoffset: 0;
}

#path_line_3.path-line {
  stroke-dasharray: 43.4 30;
  stroke-dashoffset: -30;
}

#path_line_1.path-line {
  stroke-dasharray: 43.4 30;
  stroke-dashoffset: -30;
}
<svg id="svg" version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 50 50">
        <path id="path_line_1" class="line" d="M 10 10, 40 10, 10 40" stroke-linecap="round"  stroke-linejoin="round" fill="transparent" stroke="white " stroke-width="3" />

        <path id="path_line_2" class="line" d="M 25 25, 40 25" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3"  stroke-linejoin="round"/>

        <path id="path_line_3" class="line" d="M 10 40, 40 40, 10 10" stroke-linecap="round" fill="transparent" stroke="white " stroke-width="3"  stroke-linejoin="round" />

    </svg>


text:
Q: Stacking star PSFs from an Image; aligning sub-pixel centers I have an (1727,1853) size array (image), in which I have identified stars to model a point-spread function.  Each index of the array corresponds to an image coordinate, however, the centroid of each star is given by a sub-pixel coordinate.  I must do the following

*

*Make a 2D slice of each star.  I have done this using numpy's array slicing.  However, it slices by index, and I have sub-pixel centroid coordinates, thus any kind of slice I make will place the star off-center.

*After I make a 2D slice of each star, I must stack these arrays on top of each other to make a model of the point-spread function.  This is simple as long as the sub-pixel centers of each star are aligned.
My question is what is the most efficient (and correct) way of aligning these sub-pixel coordinates and stacking each 2D slice together?
I hope this was clear.  Any help would be much appreciated. Below is a 2D slice of one of the stars (not a very good one), however it is off center because numpy slices by index and the stars have sub-pixel coordinates for their centroids.

A: You could express the centre coordinates of the pixels in each 'slice' relative to the centroid of the star, then compute a weighted 2D histogram.
First, some example data:
import numpy as np
from matplotlib import pyplot as plt

# pixel coordinates (integer)
x, y = np.mgrid[:100, :100]
# centroids (float)
cx, cy = np.random.rand(2, 9) * 100

# a Gaussian kernel to represent the PSF
def gausskern(x, y, cx, cy, sigma):
    return np.exp(-((x - cx) ** 2 + (y - cy) ** 2) / (2 * sigma ** 2))

# (nstars, ny, nx)
stars = gausskern(x[None, ...], y[None, ...],
                  cx[:, None, None], cy[:, None, None], 10)

# add some noise for extra realism
stars += np.random.randn(*stars.shape) * 0.5

fig, ax = plt.subplots(3, 3, figsize=(5, 5))
for ii in xrange(9):
    ax.flat[ii].imshow(stars[ii], cmap=plt.cm.hot)
    ax.flat[ii].set_axis_off()
fig.tight_layout()

Weighted 2D histogram:
# (nstars, ny, nx) pixel coordinates relative to each centroid
dx = cx[:, None, None] - x[None, ...]
dy = cy[:, None, None] - y[None, ...]

# 2D weighted histogram
bins = np.linspace(-50, 50, 100)
h, xe, ye = np.histogram2d(dx.ravel(), dy.ravel(), bins=bins,
                           weights=stars.ravel())

fig, ax = plt.subplots(1, 1, subplot_kw={'aspect':'equal'})
ax.hold(True)
ax.pcolormesh(xe, ye, h, cmap=plt.cm.hot)
ax.axhline(0, ls='--', lw=2, c='w')
ax.axvline(0, ls='--', lw=2, c='w')
ax.margins(x=0, y=0)


text:
Q: How to convert a Swift 5.7 Regex back to a string? It's pretty straightforward to convert a string to a regex:
let regex = try! Regex("foo")

But if I try to get the string back out of the regex, instead of foo, I get something like:

_StringProcessing.Regex<_StringProcessing.AnyRegexOutput>(program: _StringProcessing.Regex<_StringProcessing.AnyRegexOutput>.Program)

Mirrors are of marginal help here. It takes several levels of reflection to get anywhere:
let regexMirror = Mirror(reflecting: regex)
let program = regexMirror.children.first!.value // runtime type: Regex<AnyRegexOutput>.Program
let programMirror = Mirror(reflecting: program)
print(Array(programMirror.children))

[(label: Optional("tree"), value: _StringProcessing.DSLTree(root: _StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.concatenation([_StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.atom(_StringProcessing.DSLTree.Atom.char("f")), _StringProcessing.DSLTree._AST.ASTNode(ast: 「f」)), _StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.atom(_StringProcessing.DSLTree.Atom.char("o")), _StringProcessing.DSLTree._AST.ASTNode(ast: 「o」)), _StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.atom(_StringProcessing.DSLTree.Atom.char("o")), _StringProcessing.DSLTree._AST.ASTNode(ast: 「o」))]), _StringProcessing.DSLTree._AST.ASTNode(ast: (「f」,「o」,「o」))))), (label: Optional("compileOptions"), value: _StringProcessing._CompileOptions(rawValue: 0)), (label: Optional("_loweredProgramStorage"), value: nil)]

This is something that gives the appearance of being parseable, but it's full of private types and things I don't particularly care about.
Is there a simple way to get the string representation of a regex?


text:
Q: How to run PHP project with Apache from home folder Old codeignitor project just won't run due to apache problem. Tried all the solutions found in other posts and other fora, but luck so far. It's a simple problem and I think it has something to do with permissions. Yet the permission settings seem to be fine.
Firstly, the problem. This is what I see in the browser

This is what I see in the apache logs:

[Sat May 11 10:55:43.026415 2019] [core:crit] [pid 10672] (13)Permission denied: [client 127.0.0.1:38216] AH00529: /home/user_name/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable and that '/home/user_name/' is executable 127.0.0.1 - -
[11/May/2019:10:55:43 -0400] "GET / HTTP/1.1" 403 575 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"
[Sat May 11 10:55:43.314120 2019] [core:crit] [pid 10672] (13)Permission denied: [client 127.0.0.1:38216] AH00529: /home/user_name/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable and that '/home/user_name/' is executable, referer: http://my_php_site.local/ 127.0.0.1 - -
[11/May/2019:10:55:43 -0400] "GET /favicon.ico HTTP/1.1" 403 585 "http://my_php_site.local/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"

Note that apache is trying to execute a .htaccess file in /home/user_name/.htaccess
I do have a .htaccess file in the project folder, and think that's the Apache should look for.
Secondly, my environment. Just in case I miss something I will give here my whole configuration.
The project is located somewhere in my /home/user_name/ folder, and not in /var/www/.
File permissions for .htaccess:
-rwxr-xr-x  1 user_name www-data .htaccess

Project folder permissions:
drwxr-xr-x 11 user_name www-data my_php_site

Since the project is in the home folder I have a rule in my /etc/hosts file:
127.0.0.1       my_php_site.local

The apache config for my site:
<Directory /home/user_name/code/projects/my_php_site>
    Require all granted
</Directory>
<VirtualHost *:80>
        ServerName my_php_site.local
        ServerAlias my_php_site.local
        ServerAdmin webmaster@localhost
        DocumentRoot /home/user_name/code/projects/my_php_site

        ErrorLog /home/user_name/code/projects/my_php_site/logs/apache2-error.log
        CustomLog /home/user_name/code/projects/my_php_site/logs/apache2-access.log combined
</VirtualHost>

And finally, the .htaccess file itself:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?/$1 [L]

A: Solution
Apache — with user group www_data — must be able to traverse the home folder. This means it needs octal value 5, symbolic r-x.
chmod 750 /home/user_name

One Stack Overflow post mentions permissions for the project folder, but not for the home folder itself: https://askubuntu.com/questions/325498/apache-cant-access-folders-in-my-home-directory
Following steps can also be necessary, depending on versions and system:
Allow Apache to execute files in the home folder
sudo a2enmod userdir

sudo nano /etc/apache2/mods-available/php7.0.conf
Comment this part (put # at the start of each line):
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

sudo nano /etc/apache2/apache2.conf
Add this:
<Directory /home/*/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>


text:
Q: How can we get fb user's timezone with fb sender id using graph api? We have a few bots on fb messenger, and facebook sends us the user's sender id that is connected to our page and not the actual fb user id. When we try to fetch user profile with the graph api, the time zone comes incorrectly. Rest all details like user name, gender and profile picture comes correctly, so the access token and sender id are correct.
All the users' timezones come as IST (5.5), where we operate from. So I guess it has something to do with how the sender id is created, or fb is sending the time zone of our page and not the user profile. Does anyone else face similar problem?

A: It worked for me, perhaps most of your users were in the same timezone as you?
Just to make sure we're on the same page with the get request...
You can find Facebook's User profile reference here.
https://developers.facebook.com/docs/messenger-platform/user-profile
You'll have to make a get request to this url with the user's id and your app's token.
"https://graph.facebook.com/v2.6/USER_ID?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=PAGE_ACCESS_TOKEN"


text:
Q: Merging lists of lists back together R I have a loop that generates lists of lists
so the result is something like
Result = list()
Result[[1]] = c(1,2,3,6,6,4)
Result[[2]] = c(32,123,432,12, 0, 0)

desired output:
Result = c(1,2,3,6,6,4,32,123,432,12, 0, 0)

I want to merge this back into one column to add to a dataframe?
How do I do this?
I tried:
do.call(rbind, Result)

but that just stacks them into a matrix
do I then have to melt that back with tidyr?

A: Try simply this:
unlist(Result)


text:
Q: Set multiple wallpapers? As you know, since a few versions, Windows allows you to set multiple wallpapers that rotate automatically. I'm creating a  program to sync my wallpapers over my computers and I'd like to know if it's possible not to set one wallpaper (as a lot of posts show how to do), but multiple ones, as if I went to Personalize > Wallpaper > Select more than one.
I could of course use a timer to change it but it would make the software heavier and if Windows has a way to do it properly it would be way better.

A: As Reza Aghaei noted in the comments, starting with Windows 8 you can set per-monitor wallpaper programmatically using the IDesktopWallpaper::SetWallpaper COM call
There's actually a complete example given on a question concerning a different topic (how to instantiate an instance when all you know is the COM interface):

*

*https://stackoverflow.com/a/41713718/103167
That answer in turn gives credit to an open source project

*

*https://bitbucket.org/ciniml/desktopwallpaper

A: You can use Wallpaper Engine. It allows you to set an individual video for each of your monitors, or choose one from the Steam Workshop (as well as a few other features).
You can make a video out of the pictures you have and upload that to Wallpaper Engine. It's $4 on Steam.


text:
Q: get last data query from calculate and group by i am trying to make trial balance with general ledger data , the results of the trial balance in the can from the last calculation based debit-credit account name, and then group by based on each account name
GEneral ledger :
Kas :
Account  |  Debet  | KRedit  | Saldo
kas         1000      0        1000
kas         200       0        1200
kas         0         250       950

Bank :
Account  |  Debet  | KRedit  | Saldo
bank        2000      0        2000
bank         200       0        2200
bank         0         500      1700

Sale :
Account  |  Debet  |  KRedit  |   Saldo
Sale          0        2000      -2000
Sale           0        500       -2500
Sale           0        500       -3000

Result :
Account  |  Debet  |  KRedit  |
    Kas       950        0
    bank      1700      0
    sale       0        3000

There is my code :
SELECT nama_perkiraan,kredit,debet,max(@s:=@s+debet-kredit) as saldo FROM `tbl_jurnal_umum` LEFT JOIN (SELECT @s:=0) as `setVar` ON 1=1  GROUP by nama_perkiraan

Thanks

A:     sselect s.account,
         case when s.saldo > 0 then s.saldo else 0 end as debet ,
         case when s.saldo < 0 then s.saldo * -1 else 0 end as kredit
from
(
select account,
        sum(case when debet <> 0 then debet else kredit * -1 end) saldo
from generalledger
group by account
) s
where s.saldo <> 0
order by
case when s.account = 'kas' then 1
      when s.account = 'bank' then 2
      else 3
end


text:
Q: Teradata Getting value of a variable from multiple rows I have the following date and amount variables for a different dates. I need only one row per ID based on minimum of the dates.
Data I have:
 ID     Date         Code      Amt
 101    2/1/2018      A90       25
 101    2/2/2018      B90       15
 101    2/5/2018      A90       25
 102    2/1/2018      B90       10

Data I want:
 ID     A90_Date     B90_Date    A90_Amt  B90_Amt
 101    2/1/2018      2/2/2018       25    15
 102                  2/1/2018             10

My query:
Select ID,
    min(case when Code='A90' then Date else Null end) as A90_Date,
    min(case when Code='B90' then Date else Null end) as B90_Date,
    min(case when Code='A90' then Amt else Null end) as A90_Amt,
    min(case when Code='B90' then Amt else Null end) as B90_Amt
  from Table
  group by 1

Although this gives me the Date and Amount values I am concerned whether they are accurate or not from more than 1MM records. Is there an efficient way to pull this data using Qualify/Partition statements in Teradata?
Thanks for your help in advance.

A: If the amounts for the same ID/code are different, you might get wrong results. Then you must filter the earliest date before aggregation, e.g.
with cte as
 (
   Select ID, Code, Date, Amt
   from Table
   qualify row_number() over (partition by ID, Code order by date) = 1
 )
Select ID,
    min(case when Code='A90' then Date end) as A90_Date,
    min(case when Code='B90' then Date end) as B90_Date,
    min(case when Code='A90' then Amt  end) as A90_Amt,
    min(case when Code='B90' then Amt  end) as B90_Amt
from cte
group by 1

Depending on your data this might be more efficient:
Select DISTINCT ID,
    first_value(case when Code='A90' then Date end) over (partition by ID order by date) as A90_Date,
    first_value(case when Code='B90' then Date end) over (partition by ID order by date) as B90_Date,
    first_value(case when Code='A90' then Amt  end) over (partition by ID order by date) as A90_Amt,
    first_value(case when Code='B90' then Amt  end) over (partition by ID order by date) as B90_Amt
from Table
group by 1


text:
Q: How do you get compile time SDK compatibility warnings from Gradle? Was recently doing a project and mid-way we had to lower the minimum supported SDK supported in the Android manifest. Some Android API's we use are not compatible the new lower minimum SDK. We only discovered these as run time crashes. Why wouldn't the Gradle and/or the Android IDE pick up these as warnings ? Normally, I see the warnings as I code it, but for code already written, I am not warned during compilation.
I would like to be able to re-compile my project, and get all the API warnings about the minimum supported SDK. I had done some research on Lint, and it testing with it, has not yielded any results beyond warning me about XML style incompatibilities. So, I can't seem to find it for Gradle, and Android IDE is not running through the existing code already written, and raising warnings. Is this possible ? If it is, can someone provide a solution.


text:
Q: inkscape shell mode I tried to run inkscape shell mode by writing these lines in a .bat file:
inkscape --shell  >2.svg -e 2.png
But it doesn't work at all (no png  files), more over I tried to open the current svg input and I found it damaged and I failed to open it at all.
 Could any one please tell me the right command lines to enter the SHELL mode and execute other inkscape command lines.

A: You're redirecting output, using the >, to 2.svg. > means redirect output to this file.
Probably more correct would be:
rem echo the commands you want to execute to a file
echo 2.svg -e 2.png > commands.txt
echo quit >> commands.txt
inkscape --shell < commands.txt

not sure if this works because I don't use windows.

A: Exporting SVG to different formats

*

*export to bitmap (png)
inkscape -f FILENAME.svg -e FILENAME.png
loads FILENAME.svg and exports it to FILENAME.png
inkscape -f FILENAME.svg -w WIDTH -h HEIGHT -e FILENAME.png
loads FILENAME.svg and exports it to FILENAME.png with width size, WIDTH, and height size, HEIGHT, in pixels

*export to pdf
inkscape -f FILENAME.svg -A FILENAME.pdf
loads FILENAME.svg and exports it to FILENAME.pdf

*export to ps
inkscape -f FILENAME.svg -P FILENAME.ps
loads FILENAME.svg and exports it to FILENAME.ps

*export to eps
inkscape -f FILENAME.svg -E FILENAME.eps
loads FILENAME.svg and exports it to FILENAME.eps
External links:

*

*Inkscape: Guide to a Vector Drawing Program (online book)

*

*Chapter 25. Using the Command Line


text:
Q: Difference Between app.use() and router.use() in Express I was just reading the documentation on express and found these two terms, app.use(); and router.use();
I know app.use(); is used in node for Mounting a middleware at a path, and we often use it in most of the node apps. but what is router.use(); are they both same? if not, whats the difference ?
I read about router here. I also found similar questions on SO What is the difference between "express.Router" and routing using "app.get"?
 and Difference between app.all('*') and app.use('/'), but they do not really answer my question. Thanks.

A: router.use(); mounts middleware for the routes served by the specific router, app.use(); mounts middleware for all routes of the app (or those matching the routes specified if you use app.use('/ANYROUTESHERE', yourMiddleware());).
Example use case could be an app with one router with standard routes and one router that handles api routes, which need a valid user.
You would then mount the authentication middleware for the api router only with router.use(yourAuthMiddleware());.
If you would have an app though that requires a valid user for all routes, mount the middleware for the app with app.use(yourAuthMiddleware());

A: app.use() used to Mounts the middleware function or functions at the specified path,the middleware function is executed when the base of the requested path matches path.
router.use() is used to middleware function or functions, The defaults mount path to "/".
But in
app.use() you will have to give a specified path like that:
 var adsRouter = require('./adsRouter.js');
    app.use('/ads', adsRouter);

or
app.use('/ads', function(req, res, next) {

  // write your callback code here.

    });

But while using router.use() you can give only middleware, like this:
router.use(function(req, res, next) {
  console.log('%s %s %s', req.method, req.url, req.path);
  next();
});

or
router.use('/test', function(req, res, next) {
  // write your callback code here.
  next();
});

or
//in router.js

router.use('/admin', authUtil.verifySessionId, authUtil.verifyLisencee);
router.post('/admin', controllerIndex.ads.adListingAdmin);

In the above code when the end point is '/admin' then first it will call the authUtil.verifySessionId and authUtil.verifyLisencee then it will execute next line with 'admin' end point and according to  controllerIndex.ads.adListingAdmin method.

A: router.get is only for defining subpaths. Consider this example:
var router = express.Router();

app.use('/first', router); // Mount the router as middleware at path /first

router.get('/sud', smaller);

router.get('/user', bigger);

*

*If you open /first/sud, then the smaller function will get called.

*If you open /first/user, then the bigger function will get called.

In short, app.use('/first', router) mounts the middleware at path /first, then router.get sets the subpath accordingly.

But if we instead use the following:
app.use('/first', fun);

app.get('/sud', bigger);

app.get('/user', smaller);

*

*If you open /first in your browser, fun will get called,

*For /sud, bigger will get called

*For /user, smaller will get called

But remember for /first/sud, no function will get called.
This link may also help: http://expressjs.com/api.html#router

A: app.use(middleware): application-level middleware.
router.use(middleware): router-level middleware.
("middleware" refers to methods/functions/operations that are called between processing the request and sending the response.)
See https://expressjs.com/en/guide/using-middleware.html for a comparison of different types of middleware used in an Express app.

A: When looking at the express js docs for Routing (https://expressjs.com/en/guide/routing.html#express-router):

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app".

A Router created with express.Router() is no different than an app created with express() in terms of functionality; it's like a logical grouping of routes/handlers/services/databases/etc. The biggest difference is the scope that it affects. A router just affects its own scope while the app is like the master/global scope for your web/app server. You could have many routers or "apps" running on one main app/web server instance. This is why you could listen to requests on an app instance via app.listen(80) but not on a router.


text:
Q: Firestore returning undefined documentSnapshot.createTime (using webproject with javascript) I try to get the timestamps createTime and updateTime as described in the DocumentSnapshot Documentation. So far i have done the following:

*

*successfully connected firestore with my javascript webproject

*read and write data works

Thats my code trying to get the timestamps:

db.collection("users").doc("user1").get().then(doc => {
    if (doc.exists) {
        console.log(doc.createTime);  // -> undefined (?)
        console.log(doc.updateTime);  // -> undefined (?)
        console.log(doc.readTime);    // -> undefined (?)
        console.log(doc.exists);      // -> true (works)
        console.log(doc.id);          // -> "user1" (works)
    }
}).catch(error => {
    console.log("Error getting document:", error);
});

How come that the document timestamp methods are not working, whereas the other methods like exists or id work properly?

A: The createTime and updateTime you linked are available when your code runs in Cloud Functions, using the firebase-functions library.
Since your code is not running in Cloud Functions, these properties are not (currently) available. You should use the documentation here to know what properties are available for you in the regular JavaScript SDK.

A: The document of Firebase for web is this.
See:

*

*https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot.html

*https://firebase.google.com/docs/reference/js


text:
Q: .Net Xml Serialization: how to collapse misc children nodes to text? I'd like to use XmlSerializer to deserialize the following structure:
<modules>

  <module name="1">
     <config>
       <miscNodes1/>  ...
     </config>
  </module>

  <module name="2">
     someConfigString1;someConfigString2;
  </module>

</modules>

to .net classes like that:
[XmlRoot("modules")]
class Config
{
  [XmlElement("module");
  public List<Module> Modules { get; set; }
}

class Module
{
  [XmlAttribute("name")]
  public string Name { get; set; }

  [???]
  public string Config { get; set; }
}

I'd like to collapse miscellaneous children nodes inside ./modules/module to string:
"<config><miscNodes1/></module>" and "someConfigString1;someConfigString2;"  (just as if I call InnerXml for element)
XmlText doesn't help me.
How can I do that ?
Thank you in advance!

A: You can use the XmlAnyElement attribute on array of XmlNode, like this:
[XmlAnyElement]
public XmlNode[] Config { get; set; }


text:
Q: how we get custom header attributes which pass in https secure header I try to get header attributes from http header by
request.headers

But in case of HTTPS i fail to get custom header attributes.
so my concern is how i get custom attributes in case of HTTPS.


text:
Q: How can I find the innerText and outerHTML of an webpage element using the inspect window on Chome and/or Firefox? I'm trying to manually find the innerText and outerHTML of buttons on websites by right-clicking them and pressing inspect, but I don't know where I can find these properties. The screenshot below shows what I see when I right-click --> inspect the 'compose' button in Gmail. Screenshot of inspect window on Firefox after selecting 'compose' button
Any straightforward solution (for Firefox and/or Chrome) would be very much appreciated.

A: You could find it by right-clicking the element and pressing inspect and after that, by right click on the tag there is an option  Edit as HTML.
I think that would solve your problem.


text:
Q: Using AtomicInteger and CountDownLatch to generate one instance I have a class which I want to have only one instance. However, I don't want multiple threads to call getInstance(). So I have coded it in the following way
public class SomeService implements Provider<String, Claims>{

    private SomeService(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // single instance
    private static SomeService instance = null;

    private String a;
    private static AtomicInteger initialized = new AtomicInteger();
    private static CountDownLatch latch = new CountDownLatch(1);
    private String b;
    private String c;

    public static SomeService getInstance(String a, String b, String c) {
       if ( initialized.incrementAndGet() == 1) {
           instance = new SomeService(a, b, c);
           latch.countDown();
       } else {
           try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       }
       return instance;

    }

    // Other implementation code

    }

My intention (as well as understanding about this) is that:

*

*When a thread calls getInstance it will atomically increment and check whehther it's desired value.

*If not, it will wait for the other thread to open the latch which means initialization is in progress.
It would be helpful if someone helps me correct my mistakes. Seems to me that I can probably just do synchronized(someLockObject) {} block but I was wondering if this makes sense at all.

A:
My intention (as well as understanding about this) is that:
1) When a thread calls getInstance it will atomically increment and
  check whehther it's desired value.

Yes.

2) If not, it will wait for the other thread to open the latch which
  means initialization is in progress.

Yes.

Seems to me that I can probably just do synchronized(someLockObject) {} block

Yes, and that would be more typical.

I was wondering if this makes sense at all.

The code will work as you seem to intend, unless getInstance() is invoked enough times for initialized to wrap back around to 0.  I'd be inclined to use an AtomicBoolean and its compareAndSet() method instead, however, as that seems to model the situation better (and it poses no risk whatever of wraparound).
I would be more inclined to use synchonization, however, until and unless that proved to present an unresolvable performance issue.  It is clearer and more accessible.
But the approach seems poorly conceived overall, inasmuch as a thread that invokes getInstance() with one set of arguments may receive an instance that was initialized with a different set of parameters.  That may be a sign that instead of this variation on the Singleton pattern, you would be better off with the "just use one" pattern.  Note in particular that some people consider Singleton an antipattern.

A: I guess the design is fundamentally wrong here. what I believe I should be doing is
1) Put more abstraction layer and ensure that a builder pattern is used.
2) When my service needs to serve, it can use the initialization properties to determine what builder to use and then do that job.
3) If possible, I can also combine it with a factory.
Don't know if the above makes sense, but this removes the need for antipattern or "Singleton".


text:
Q: UI-Router with Nested Views I am having an issue getting UI-router working with  Nested Views.  I have a simple layout page with a Header, Nav, mainContainer.  I am just trying to get the Header and Nav injected as a Layout page and the mainContent will be driven from the Resource Pages.
However nothing shows up besides the initial layout.
I have created a Plunker to show the markup and code.
Plunker Project
Any assistance is greatly appreciated.
 <!DOCTYPE html>

    <title>{{PageTitle}}</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

Script.js
var app = angular.module('Portal', [ 'ui.router'  ]);   //, 'ngRoute', 'ngMessages',

app.config(function ($stateProvider) {

    $stateProvider
  .state('root',{
          url: '',
          abstract: true,
          views: {
            'header': {
              templateUrl: 'Header.html'

            },
            'profile':{
              templateUrl: 'Profile.html'

            },
            'nav':{
                templateUrl: 'Nav.html'
            }
          }
        });

    $stateProvider
    .state('root.index', {
          url: '/',
          views: {
            'mainContainer': {
              templateUrl: 'Sample.html'
            }
          }
        });

});

Header.html

  This is the Text that should be in the heaeder

I use the same sample text for each nest view.

A: Multiple issues:
1) check your templateUrl specification for profile view.
It is pointing to a  file that does not exist. templateUrl: 'Profile.html' You have named your file as 'Porfile.html'.
2) You are missing default route to "/". You corrected config should look like as follows:
app.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/');

    $stateProvider
     .state('root',{
          url: '',
          views: {
            'header': {
              templateUrl: 'Header.html'

            },
            'profile':{
              templateUrl: 'Porfile.html'

            },
            'nav':{
                templateUrl: 'Nav.html'
            }
          }
        });

    $stateProvider
    .state('root.index', {
          url: '/',
          views: {
            'mainContainer': {
              templateUrl: 'Sample.html'
            }
          }
        });

});

3) Then in your index.html you are missing the script src tag for your javascript