text:
Q: SQL Azure Sharding and Social Networking Apps The concept of sharding on SQL azure is one of the top recommended options to get over the 50Gb DB size limit, it has at the moment. A key strategy in sharding is to group related records called atomic units together in a single shard , so that the application needs to only query a single SQL azure instance to retrieve the data.
However in applications such as Social networking Apps, grouping a atomic unit in a single shard is not trivial, due to the inter-connectivity of entities and records. what could be a recommended approach based on such a scenario?
Also in a sharded DB , what primary keys should be used for the tables ? Big Int or GUID. i currently use BIGINT Identity columns but if the data was to be merged for some reason this would be a problem due to conflicts between the values in different shards. i have heard some people recommend GUID's (UniqueIdentifier) but i'm wary on how this could affect performance. Indexing On-premise SQL servers with UniqueIdentifier columns is not possible, and i wonder how SQL azure implements similar strategies if i were to employ a UniqueIdentifier column.

A: For a social networking app, I'd presonally forgo using SQL and instead leverage a noSQL solution such as MongoDB or Azure Table Storage. These non-normalized but in-expensive systems allow you to create multiple entity datasets that are customized to your various indexing needs.
So instead of having something like...
User1 -< relationshiptable -< User2
You'd instead have tables like
Users
User1's Friends
User2's Friends
If Users 1 and 2 are both friends, then you'd have two entries to define that relationship, not one. But if makes retrieving a list of a specific user's friends trivial. It also now opens you up for executing tasks in parallel, by searching multiple index tables at a time.
This process scales extremely well, but does require that you invest more time in how the relationships are maintained. Admittedly, this is a simiplied example. Things get much more complex when you start discussing tasks like searching across your entire user base.


text:
Q: Saving Extension Config Data Magento I've been trying to figure out exactly how does magento save the config data for a module given in  System.xml. reason?I would like to edit the data provided by the user before storing it in the database.
Any clues????

A: Take a look at Mage_Core_Model_Store::setConfig function (and getConfig for reading the value). You will probbably have to write an observer that will listen to store_save_before event.
Magento stores configuration data in core_config_data database table - path column is the hierarhical structure of XML elements in system.xml file and is the same as XPath used for reading the default value out of config.xml file and value column contains the value that was saved.
When accessing the data with for e.g. Mage::getStoreConfig( 'path', $storeId ); Magento first searches the table for path-value pair and if it doesn't find it it reads the default value from config.xml file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: proguard + maven + android Error: Method must be overridden in [proguard.optimize.peephole.ClassMerger] if ever called I'm getting an error saying something like below while running proguard through maven. What I dont understand is that it works with ANT without any problem. in additional maven can output 2 files called seeds.txt and usage.txt before get actually crashed, then it failures because of some reason which is I didn't know.
I searched for the error ("Method must be overridden in [proguard.optimize.peephole.ClassMerger] if ever called") on the internet and tried to apply advices but nothing did solve the problem. Is there someone could give any advice to me? I'm really stucked at this point.
utjars, 'D:\Projects\MavenInHerd\Android\SOP\trunk\target\proguard-obfuscated.ja
r', -dump, 'D:\Projects\MavenInHerd\Android\SOP\trunk\target\proguard\dump.txt',
 -printseeds, 'D:\Projects\MavenInHerd\Android\SOP\trunk\target\proguard\seeds.t
xt', -printusage, 'D:\Projects\MavenInHerd\Android\SOP\trunk\target\proguard\usa
ge.txt', -printmapping, 'D:\Projects\MavenInHerd\Android\SOP\trunk\target\progua
rd\mapping.txt']
[INFO] Note: there were 185 duplicate class definitions.
[INFO]       You should check if you need to specify additional program jars.
[INFO] Error: Method must be overridden in [proguard.optimize.peephole.ClassMerg
er] if ever called
[INFO] ------------------------------------------------------------------------

A: Problem is solved. Before start to explain how did I solve the problem I'm going to mention how it was working with ANT without problem but wasn't through maven. It was running with ANT because ANT was looking for project.properties file and its configuration was like below
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

Above, my proguard.txt was merging with base proguard-android.txt. Eventually ant was looking for just 1 content.
but maven did not know anything about project.properties which was the problem. The solution was merging these 2 files (my proguard-project.txt and ${sdk.dir}/tools/proguard/proguard-android.txt) manually.


text:
Q: Saving master detail entities I have a small invoicing app where I have (InvoiceMaster) and (InvoiceDetails) entities, now I am facing a problem on how to save the Master and Details together in the same time / in other words in one transaction...
I already have the following classes in my application:
- InvoiceMasterDAO
- InvoiceDetailsDAO

- InvoiceMasterService
- InvoiceDetailsService

and I was thinking shall I call the InvoiceMasterDAO, InvoiceDetailsDAO save method from within the InvoiceMasterService class? But if I did this then there is no use for the InvoiceDetailsService class?
OR Shall I just create an InvoiceService class and use to to control both InvoiceMasterDAO, InvoiceDetailsDAO in the same time?
Taking in consideration that saving an invoice for me means, saving master, saving details, deducting product balances.....OR rollback everything in case something went wront
Kindly advice

A: It's up to you, but having an InvoiceService looks like the more logical to me.
Services shouldn't be designed as one service per entity. They should be designed as a logical group of ... services that the caller needs (the UI layer, usually). In other words, they should be use-case oriented, and not entity-oriented.


text:
Q: Is the tensor product of two Yetter-Drinfeld modules a Yetter-Drinfeld module? Let $U,V$ be two Yetter-Drinfeld modules over a bialgebra $H$. Is $U \otimes V$ a Yetter-Drinfeld modules over $H$? Thank you very much.

A: Yes. Yetter-Drinfeld modules over a bialgebra form a tensor category.
You need to check that the following holds

$\left(h_{(1)}\rhd(v\otimes w)\right)^{(-1)}h_{(2)}\otimes \left(h_{(1)}\rhd(v\otimes w)^{(0)}\right)=\\=h_{(1)}\left(v\otimes w\right)^{(-1)}\otimes h_{(2)}\rhd\left(v\otimes w\right)^{(0)}$

where $\Delta h=h_{(1)}\otimes h_{(2)}$ and $\delta(v\otimes w)=(v\otimes w)^{(-1)}\otimes (v\otimes w)^{(0)}$ is a coaction on tensor product (You should know that the simultaneous modules and comodules form tensor category, hence it is well-defined).

A: We have
\begin{align}
& h.(v \otimes w) = h_{(1)}.v \otimes h_{(2)}.w, \\
& \delta(v \otimes w) = v_{(-1)} w_{(-1)} \otimes v_{(0)} \otimes w_{(0)}.
\end{align}
Therefore
\begin{align}
& ( h_{(1)}.(v \otimes w) )_{(-1)} h_{(2)} \otimes ( h_{(1)}.(v \otimes w) )_{(0)} \\
& = ( h_{(1)}.v \otimes h_{(2)}.w )_{(-1)} h_{(3)} \otimes ( h_{(1)}.v \otimes h_{(2)}.w )_{(0)} \\
& = ( h_{(1)}.v )_{(-1)} ( h_{(2)}.w )_{(-1)} h_{(3)} \otimes ( h_{(1)}.v)_{(0)} \otimes (h_{(2)}.w )_{(0)} \\
& = ( h_{(1)}.v )_{(-1)}  h_{(2)} w_{(-1)} \otimes ( h_{(1)}.v)_{(0)} \otimes h_{(3)}.w_{(0)} \\
& =  h_{(1)} v_{(-1)} w_{(-1)} \otimes  h_{(2)}.v_{(0)} \otimes h_{(3)}.w_{(0)} \\
& =  h_{(1)} (v \otimes w)_{(-1)} \otimes  h_{(2)}.(v \otimes w)_{(0)}.
\end{align}


text:
Q: Find and replace a string, and to overwrite on the same file using batch script I'm very new to scripting, and I'm looking for some kind souls here who can help me.
I want to replace the contents ("8888" with "9999") in a file known as Version.dll. I also want to save in the same filename after the script runs. It did not work.
I have to resort to creating a new file "Version1.dll" to make it work, but this is not what I wanted.
May I know if anyone can guide me, to overwrite in the same existing file (Version.dll), after I run the script? Thank you.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "filename1=%C:\Users\XXX\Desktop\Version.dll"
SET "outfile=%C:\Users\XXX\Desktop\Version1.dll"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
SET "line=%%a"
SET "line=!line:8888=9999!"
ECHO !line!
)>"%outfile%"

GOTO :EOF`


text:
Q: Unable to style h1 tag and its contents  <% provide(:title, @user.name) %>

      <%= gravatar_for @user %>
      <%= @user.name %>

My .html.erb is given above as follows, I'm trying to style the @user.name variable under h1 tag but I'm unable to do so. When I inspect element I'm able to style everything under the h1 tag directly but no luck trying with my actual css file.
 aside {
 h1 {
  font-size: 1.4em;
  text-align: left;
  letter-spacing: -1px;
  margin-bottom: 3px;
  margin-top: 0px;
 }
}

A: Please check now.

aside h1{

     font-size: 1.4em;
  text-align: left;
  letter-spacing: -1px;
  margin-bottom: 3px;
  margin-top: 0px;
}

      Header

A: Try Using
.user_info h1{

  font-size: 1.4em;
  text-align: left;
  letter-spacing: -1px;
  margin-bottom: 3px;
  margin-top: 0px;
 }

A: this will work for you
aside h1{
  color: red!important;
}

hoewever I dont recommend using important but in your case we need to debug your code and apply css precedence accordingly
meanwhile you can try below code and see if it works for you
body aside .user-info h1{
  color: red;
}


text:
Q: Does jQuery ship with SharePoint? Currently, we want to upgrade jQuery in our products, so I want to know if SharePoint use jquery in its js? It will help us to make decision about which jquery version we are going to use. I try to find jquery reference in SharePoint 2010, but I didn't find it. Does it mean there is no jQuery in SharePoint?
I found there is a js called "mQuery.js" in SharePoint 2013, the usage is quite similar with jQuery, and even most of the events'name are same. Why does Microsoft create a js for SharePoint 2013 instead of using jQuery directly? Because some functions in jQuery are unnecessary? Or for easy maintenance?
Thanks in advance!

A: In SharePoint 2010 there is no JQuery by default. So basically SharePoint uses just JavaScript etc.
If you want to use JQuery in your own solutions or some client side programmint etc, you normally have to register the JQuery library in the master page.
Hope it helps


text:
Q: django updating user profile form forms.py
class UserProfileForm(forms.ModelForm):
    phone = forms.CharField(max_length = 15,widget = forms.TextInput(attrs = {'placeholder':'Enter mobile no. ','class':''}))
    profession = forms.CharField(max_length= 50,widget = forms.Select(choices = PROFESSION_CHOICES,attrs = {'class':''}))
    #email = forms.EmailField(label='Email address',max_length = 75,widget = forms.TextInput(attrs={'placeholder':'Email address.','class':''}))
    sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''}))
    first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''}))
    last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''}))
    location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''}))
    def clean_first_name(self):
        first_name = self.cleaned_data['first_name']
        if first_name == '':
            raise forms.ValidationError("This field is required.")
        return first_name

        def save(self,*args,**kw):
                    self.instance.first_name = self.cleaned_data.get("first_name")
                    self.instance.last_name = self.cleaned_data.get("last_name")
                    self.instance.sex = self.cleaned_data.get("sex")
                    self.instance.location = self.cleaned_data.get("location")
                    self.instance.profession = self.cleaned_data.get("profession")
                    self.instance.phone = self.cleaned_data.get("phone")
                    self.instance.save()
                    return self.instance

    class Meta:
        model = User
        fields = ('username','first_name','last_name','phone','sex','profession','location')

views.py
def profile(request,nav="profile",template="profile.html",context = {},extra_context = None):
    if request.POST:
        if 'profileFormSubmit' in request.POST:
            pform = UserProfileForm(request.POST,instance = request.user)
            if pform.is_valid():
                try:
                    user = pform.save()
                    return redirect(profile,nav="profile")
                    except RuntimeError as e:
                    return HttpResponse(e)

error
The User could not be changed because the data didn't validate.

line
    user = super(UserProfileForm,self).save(*args,**kw)

doubt
what changes am i supposed to make to get rid of this error
how am i supposed to change the  , i have tried removing all the clean_field form methods , but still getting the same error , please help , thanks in advance.

A: You are calling save on your form before you clean. And you are calling save twice. Once at the start of the form save. And once at the end.
pform.is_valid() returns a boolean that you never check.
docs on modelforms

A: The form wasn't validating because I was using 'username' in my meta class of the UserProfileForm, which wasn't supposed to be there.


text:
Q: Efficiently "drilling down" into XML tree with xlinq? I'm writing a program to parse some third-party XML files. The structure is something like...
<CharacterSheet>
    ...
    <StatBlock>
        ...
        <Stat>
            ...
            <alias />
            ...
        </Stat>
        ...
    </StatBlock>
    ...
</CharacterSheet>

I'm using this in to get some practice with linq, and I'm fining I have to write some really ugly chained queries to get what I want, a list of stats and all their alias.
var CharSheet = from i in character.Elements()
        where i.Name == "CharacterSheet"
        select i;

var StatBlocks = from sheet in CharSheet
         from statBlock in sheet.Elements()
         where statBlock.Name == "StatBlock"
         select statBlock;

var stats = from statBlock in StatBlocks
        from stat in statBlock.Elements()
        select stat;

var statAliases = from stat in stats
          from alias in stat.Elements()
          where alias.Name == "alias"
          select new { stat, alias };

And I realize I could make that into one really long query using "into" (which is originally how I had it), but that just made it even more dense and difficult to work with.
It seems like there's got to be a simpler way to do what I'm trying to do.

A: You could use XPathSelectElements() (which might be a better idea, to be honest), or you could use the Elements() extension method:
var query = character.Elements("CharacterSheet")
                     .Elements("StatsBlock")
                     .Elements()
                     .Elements("alias")
                     .Select(x => new { stat=x.Parent, alias=x};


text:
Q: Query parameterized but '[' not giving search-results. VB.NET Framework 4. Entity to ESQL The following are company name in my database. I am trying to produce on the fly string query that are foolproof against SQL Injection.
I test the safety tolerance level of parameterized query against SQL Injection because I hear rumors it is not 100%.
=====userinput pure strings but with malicious content for SQL injection=========
userinput = "Tubo'; UPDATE STOCK_TYPE SET Description='SQL Injection'" &
            "WHERE STock_Type_ID=1; --'"

userinput = "'Some Name''; GRANT CONTROL TO [Malicious User]; PRINT ''Game over!" &
            "This system is no longer yours!''" &
            "-- Malicious User now can control the database!!!'"

userinput = "!!!@@@###$$$%%%^^^&&&***((()))///```~~~___---+++===:::;;;"""'''|||
             \\\}}}>>><<<{{{}}}]]]...,,,[[[]]]///"

=====To search company name with SQL Injected userinput ==========================
Dim SQL = "select p.Name from EntContext.COMPANIes as p Where p.Name like @CompanyName"

ObjectParamters.Add(New ObjectParameter("@CompanyName", userinput))

Dim databaseObjectQuery As ObjectQuery(Of DbDataRecord) =
     New ObjectQuery(Of DbDataRecord)(SQL, EntContext)

databaseObjectQuery.Parameters.Add(parameter)

====================================================================
COMPANIes.name database contain exactly these strings to help my testing.
By a successful search against user input I think my code is stronger against attack.
But when I search against COMPANIes.name with the exact user input string, only the first userinput produced result.
I narrow the culprit to '[' it doesn't produce result for second and third userinput via LINQPAD
select p.company_id , p.Name
from EntContext.COMPANIes as p
Where  p.Name like '%[%'

No result. So do this
select p.company_id , p.Name
from EntContext.COMPANIes as p
Where  p.Name like '%/[%' escape '/'

produce the result against second and third user input over matching '[' in company name.
================Attempt to solve programmatically in VB.NET ===============
FilterSQL = " AND COMPANies.Name like @CompanyName escape " + Chr(255)
objectParameters.Add(New ObjectParameter("CompanyName", "%" & Chr(255) &
searchResultParam.ParamValue.Value & "%"))

 The simple identifier 'ÿ' must contain basic Latin characters only.
 To use UNICODE characters, use an escaped identifier. Near line 1, column 320.

=============================================================================

*

*Are parameterized query 100% foolproof even userinput is coded like this?
ObjectParamters.Add(New ObjectParameter("@CompanyName", userinput))

*Was my assumption over second and third userinput correct on escaping this character '[' ?

*In parameterized query of LINQ, how do search against this exact stored value?
COMPANIes.Name= "!@#$%^&*()/`~_-+=:;"'|}><{}].,[]/"

A: A breakthrough with this code
FilterSQL = " AND COMPANies.Name like @CompanyName escape '['"
Dim escCrit As String = "%" & ParamValue.Value.Replace("[", "[[") & "%"
objectParameters.Add(New ObjectParameter("CompanyName", escCrit ))

Here's actual and literal ID & Name stored in my COMPANies.Name column.

*

*Tubo'; UPDATE STOCK_TYPE SET Description='SQL Injection' WHERE STock_Type_ID=1; --'

*'Some Name''; GRANT CONTROL TO [Malicious User]; PRINT ''Game over! This system is no longer yours!''-- Malicious User now can control the database!!!'

*!!!@@@###$$$%%%^^^&&&*((()))///```~~~_---+++===:::;;;"""'''|||\}}}>>><<<{{{}}}]]]...,,,[[[]]]///???'''

*?!@#$%^&*()/`~_-+=:;"'|}><{}].,[]/ȸ
============================================================
Enter userinput in textbox and click Search. Test results:
userinput = Tubo'; UPDATE STOCK_TYPE SET Description='SQL Injection' WHERE STock_Type_ID=1; --'

Company ID 1 found
userinput = 'Some Name''; GRANT CONTROL TO [Malicious User]; PRINT ''Game over! This system is no longer yours!'' -- Malicious User now can control the database!!!'

Company ID 2 found
userinput = !!!@@@###$$$%%%^^^&&&***((()))///```~~~___---+++===:::;;;"""'''|||
         \\\}}}>>><<<{{{}}}]]]...,,,[[[]]]///

Company ID 3 found
userinput = ?!@#$%^&*()/`~_-+=:;"'|}><{}].,[]/ȸ

Company ID 5 found
userinput = [

Company ID 2, 3 and 5 found
userinput = []

Company ID 3 and 5 found
userinput = [[[

Company ID 3 found
This answers my third question. I did not have to filter any input and not necessary limit to textbox search criteria only. This mode accomodate even special characters, especially useful in the case of storing public comments from your users in your database. They could type anything in their text block. I don't know why '[' needs to be specifically code as an escape. I think it's a bug, the entity framework team forgot to escape '['. They do however escape everything else I have tested so far. Note the character ȸ Latin Small Letter Db Digraph is intentional.
I wonder what magic happened. I think the SQL is sent separately from the parameter. When SQL never meet parameter, we can never get SQL Injection. Impossible because the modality of SQL Injection depend on dirty SQL. But SQL never met Injection. My test case on range of special characters suggests this.
I think the implementation implicitly use sp_executesql at the backend from LINQ. In the backend, the SQL goes through execution planning while parameters were matched as string literal. I just have to be careful that my SQL never 'meet' user input whether from frontend or database backend.


text:
Q: Why does the Dequantize node fail to prepare? Background
I'm playing around with MediaPipe for hand tracking and found this useful wrapper for loading MediaPipe's hand_landmark.tflite model. It works without any problems for me on Ubuntu 18.04 with Tensorflow 1.14.0.
However, when I try use a newer recently released model, I run into the following error:
INFO: Initialized TensorFlow Lite runtime.
Traceback (most recent call last):
  File "/home/user/code/.../repo/models/test_model.py", line 12, in <module>
    use_mediapipe_model()
  File "/home/user/code/.../repo/models/test_model.py", line 8, in use_mediapipe_model
    interp_joint.allocate_tensors()
  File "/home/user/code/env/lib/python3.6/site-packages/tensorflow/lite/python/interpreter.py", line 95, in allocate_tensors
    return self._interpreter.AllocateTensors()
  File "/home/user/code/env/lib/python3.6/site-packages/tensorflow/lite/python/interpreter_wrapper/tensorflow_wrap_interpreter_wrapper.py", line 106, in AllocateTensors
    return _tensorflow_wrap_interpreter_wrapper.InterpreterWrapper_AllocateTensors(self)
RuntimeError: tensorflow/lite/kernels/dequantize.cc:62 op_context.input->type == kTfLiteUInt8 || op_context.input->type == kTfLiteInt8 was not true.Node number 0 (DEQUANTIZE) failed to prepare.

When looking at the two models in Netron, I can see that the newer model uses nodes of the type Dequantize which seem to cause the problem. As I'm a beginner when it comes to Tensorflow I don't really know where to go from here.
Code to reproduce the error
from pathlib import Path
import tensorflow as tf

def use_mediapipe_model():
    interp_joint = tf.lite.Interpreter(
        f"{Path(__file__).parent}/hand_landmark.tflite") # path to model
    interp_joint.allocate_tensors()

if __name__ == "__main__":
    use_mediapipe_model()

Question
Is the problem related to the version of Tensorflow that I'm using or am I doing something wrong when it comes to loading the .tflite models?

A: Doesn't work in TF 1.14.0. You need at least 1.15.2


text:
Q: Directive formatting does not keep up with fast input I am trying to format an input field by transforming the letters by the user to valid initials: Uppercase, separated by a dot.
Input has to formatted as the user types and not afterwards.
new-customer-form.component.html
<input formatInitials>

format-initials.directive.ts
import { Directive, HostListener } from "@angular/core";

@Directive({
    selector: '[formatInitials]'
})
export class FormatInitialsDirective {
    @HostListener('keyup', [ '$event' ]) private format(event: KeyboardEvent): void {
        const {target} = event;
        const {value} = target;

        const isAlphabeticKeyCode = event.keyCode >= 65 && event.keyCode <= 90;

        if (isAlphabeticKeyCode) { // Only separate with a dot for alphabetic chars
            target.value = `${value.toUpperCase()}.`;
        }
    }

}

When I type slow the formatting works fine, but when I type faster the formatting gets messed up so instead of P.J.S I get PJ.S...
It looks like the input is being processed before the directive ran.
How can I make sure the input is only processed once the formatting has happened?

A: As mentioned in the previous answer, keyup cannot be used as you don't necessary leave a key before pressing the next key while typing fast.
You need to use keydown instead along with preventDefault() to manipulate the input entered before placing it in the input.
Try this in your directive
import { Directive, HostListener } from "@angular/core";

@Directive({
  selector: '[formatInitials]'
})
export class FormatInitialsDirective {
  @HostListener('keydown', ['$event'])
  private format(event: KeyboardEvent): void {
    const { target } = event;
    const { value } = target;

    const isAlphabeticKeyCode = event.keyCode >= 65 && event.keyCode <= 90;

    if (isAlphabeticKeyCode) {
      event.preventDefault();
      target.value += `${event.key.toUpperCase()}.`;
    }
  }
}

Here is a working example on StackBlitz

A: With the above ansfer from @nash11 I got it to work, but was having trouble retaining the value in my form, so I've added the part about updating the value of the formControl here:
import { Directive, HostListener, Input } from '@angular/core';
import { FormControl } from '@angular/forms';

@Directive({
    selector: 'input[formatInitials]',
})
export class FormatInitialsDirective {
    @Input() public formControl: FormControl;

    @HostListener('keydown', ['$event'])
    public format(event: KeyboardEvent): void {
        const { target } = event;
        const isAlphabeticKeyCode = event.keyCode >= 65 && event.keyCode <= 90;

        if (isAlphabeticKeyCode) {
            event.preventDefault();
            (<HTMLInputElement>target).value += `${event.key.toUpperCase()}.`;
            this.formControl.setValue((<HTMLInputElement>target).value);
        }
    }
}


text:
Q: Problems with relative import I run a file called test.py which has an import like this
from .nms.cpu_nms import cpu_nms, cpu_soft_nms
from .nms.gpu_nms import gpu_nms

When I run the file though, I get this error:
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    from utils.nms_wrapper import nms
  File /media/ryan/shakira/InsightFace_Pytorch/FaceBoxes.PyTorch/utils/nms_wrapper.py",     line 7, in <module>
    from .nms.cpu_nms import cpu_nms, cpu_soft_nms
ModuleNotFoundError: No module named 'utils.nms.cpu_nms'

I have tried doing
sys.path.append('/path/to/the/main/directory/')
But that too does not work,
EDIT:
This is my directory structure:
FaceBoxes.PyTorch/
├── data
│   ├── AFW
│   │   └── img_list.txt
│   ├── config.py
│   ├── data_augment.py
│   ├── FDDB
│   │   └── img_list.txt
│   ├── __init__.py
│   ├── PASCAL
│   │   └── img_list.txt
│   ├── __pycache__
│   │   ├── config.cpython-36.pyc
│   │   ├── data_augment.cpython-36.pyc
│   │   ├── __init__.cpython-36.pyc
│   │   └── wider_voc.cpython-36.pyc
│   ├── WIDER_FACE
│   │   └── img_list.txt
│   └── wider_voc.py
├── layers
│   ├── functions
│   │   ├── prior_box.py
│   │   └── __pycache__
│   │       └── prior_box.cpython-36.pyc
│   ├── __init__.py
│   ├── modules
│   │   ├── __init__.py
│   │   ├── multibox_loss.py
│   │   └── __pycache__
│   │       ├── __init__.cpython-36.pyc
│   │       └── multibox_loss.cpython-36.pyc
│   └── __pycache__
│       └── __init__.cpython-36.pyc
├── LICENSE
├── make.sh
├── models
│   ├── faceboxes.py
│   └── __init__.py
├── README.md
├── test.py
├── train.py
└── utils
    ├── box_utils.py
    ├── build.py
    ├── __init__.py
    ├── nms
    │   ├── cpu_nms.c
    │   ├── cpu_nms.pyx
    │   ├── gpu_nms.cpp
    │   ├── gpu_nms.hpp
    │   ├── gpu_nms.pyx
    │   ├── __init__.py
    │   ├── nms_kernel.cu
    │   ├── __pycache__
    │   │   └── __init__.cpython-36.pyc
    │   └── py_cpu_nms.py
    ├── nms_wrapper.py
    ├── __pycache__
    │   ├── box_utils.cpython-36.pyc
    │   ├── __init__.cpython-36.pyc
    │   └── nms_wrapper.cpython-36.pyc
    └── timer.py

Any suggestions would be really helpful, Thanks in advance.

A: There was no error in the imports, The problem was that there was a cython file which i had to compile which i had glossed over.And once i had compiled,the problem disappeared.


text:
Q: PHP Error in number_format i have this variable: $this->{$prefix . '_total'} that can equal any number depending on the case but for the time being lets say $this->{$prefix . '_total'} = 4000.
So i use $this->{$prefix . '_total'} in order to get 4,000.
However, i dont know why but i get 4 instead.
Whats happening to the other zeros?? I tried with different values such as 1564.13 for example and in all cases the output its only the very first number. So i tried it like this:
number_format(($this->{$prefix . '_total'}*100000))

and it doesnt work either! I still get only the first digit. Why?? This blows my mind at so many levels. Please help.
Thank you.
Full function:
function render($indent = "", InvoicePayment $payment = null)
{
$prefix = (!is_null($payment) && !$payment->isFirst()) ? 'second' : 'first';
$tm_added = is_null($payment) ? $this->tm_added : $payment->dattm;

$newline = "\r\n";

$price_width = max(mb_strlen(Am_Currency::render($this->{$prefix . '_total'}, $this->currency)), 8);

$column_padding = 1;
$column_title_max = 60;
$column_title_min = 20;
$column_qty = 4 + $price_width;
$column_num = 3;
$column_amount = $price_width;
$space = str_repeat(' ', $column_padding);

$max_length = 0;
foreach ($this->getItems() as $item) {
    $max_length = max(mb_strlen(___($item->item_title)), $max_length);
}

$column_title = max(min($max_length, $column_title_max), $column_title_min);
$row_width = $column_num + $column_padding +
             $column_title + $column_padding +
             $column_qty + $column_padding +
             $column_amount + $column_padding;

$column_total = $column_title +
                $column_qty + $column_padding;
$total_space = str_repeat(' ', $column_padding + $column_num + $column_padding);

$border = $indent . str_repeat('-', $row_width) . "$newline";

$out = $indent . ___("Invoice") . ' #' . $this->public_id . " / " . amDate($tm_added) . "$newline";
$out .= $border;
$num = 1;
foreach ($this->getItems() as $item) {
    $title = explode("\n", $this->wordWrap(___($item->item_title), $column_title, "\n", true));
    $out .= $indent . sprintf("{$space}%{$column_num}s{$space}%-{$column_title}s{$space}%{$column_qty}s{$space}%{$price_width}s$newline",
        $num . '.', $title[0], $item->qty . 'x' . Am_Currency::render($item->{$prefix . '_price'}, $this->currency), Am_Currency::render($item->{$prefix . '_total'}, $this->currency));
    for ($i=1; $i<count($title); $i++)
        $out .= $indent . sprintf("{$space}%{$column_num}s{$space}%-{$column_title}s$newline", ' ', $title[$i]);
    $num++;
}
$out .= $border;
if ($this->{$prefix . '_subtotal'} != $this->{$prefix . '_total'})
    $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s$newline", ___('Subtotal'), Am_Currency::render($this->{$prefix . '_subtotal'}, $this->currency));
if ($this->{$prefix . '_discount'} > 0)
    $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s$newline", ___('Discount'), Am_Currency::render($this->{$prefix . '_discount'}, $this->currency));
if ($this->{$prefix . '_shipping'} > 0)
    $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s$newline", ___('Shipping'), Am_Currency::render($this->{$prefix . '_shipping'}, $this->currency));
if ($this->{$prefix . '_tax'} > 0)
    $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s$newline", ___('Tax'), Am_Currency::render(number_format($this->{$prefix . '_tax'}), $this->currency));
$out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s$newline", ___('Total'), Am_Currency::render($this->{$prefix . '_total'}, $this->currency));
$out .= $border;
if ($this->rebill_times) {
    $terms = explode("\n", $this->wordWrap(___($this->getTerms()), $row_width, "\n", true));
    foreach ($terms as $term_part)
        $out .= $indent . $term_part . $newline;
    $out .= $border;
}
return $out;
}

And this is the render function
static function render($value, $currency = null, $locale = null)
    {
        return (string)self::create($value, $currency, $locale);
    }

 public function __toString()
    {
        $format = array_key_exists($this->currency, $this->formats) ?
            $this->formats[$this->currency] :
            '%.2f %s';
        return sprintf($format, $this->value, $this->currency);
    }

A: Try this
<?php
   echo number_format($number,0,'',',');
?>

A: Stabbing into the dark here to explain the phenomenon:
echo (int)number_format(1000);

This results in "1". Because number_format produces "1,000", and (int) tries to parse it back into an integer, and since "," is not a valid part of an integer specification that's where it stops and returns only "1". See http://php.net/manual/en/language.types.string.php#language.types.string.conversion.
Something like this must be happening in your Am_Currency::render.


text:
Q: Splitting pattern into multiple tables with gmatch I am trying to gsplit my text into multiple tables using a pattern.
So this is my input.
\x10Hello\x0AWorld
This is what I expect in my output,
\x0A <- similar inputs will always be 4 chars long
{{'\x10', 'Hello'}, {'\x0A', 'World'}}
This is what I have tried so far.
local function splitIntoTable(input)
    local output = {}
    for code, text in (input):gmatch('(\\x%x+)(.*)') do
        print(code .. ' ' .. text);
        table.insert(output, { code, text })
    end
    return output
end

I made 2 regex groups in gmatch the first group is for the hex and the second group is for the text, I am not sure why this isn't working. The print statement never gets executed so the loop is never being used.

A: The pattern '\\x%x+' matches a literal backslash, an x, and a sequence of hex digits. It does not match the ASCII character generated by a hexadecimal escape such as '\x0A'.
You need to replace it with a character class in square brackets such as '[\x10\x0A]'. You will have to fill in the character class with whatever ASCII characters (or other bytes) you are expecting in that position in the match.
Unfortunately, this pattern will only match once in a string like '\x10Hello\x0AWorld'. The second part of the pattern also needs to be modified.
local function splitIntoTable(input)
    local output = {}
    for code, text in (input):gmatch('([\x10\x0A])(.*)') do
        print(code .. ' ' .. text);
        table.insert(output, { code, text })
    end
    return output
end


text:
Q: How to pass translations from a module to a smarty template in prestashop? I'm building a module, and have somethins like this:
$custom_menu = '
'.
  '
' . $this->l("Collections") . $this->get_collections_menu($collections) . '
'.
  '
' . $this->l("Styles") . $this->get_styles_menu($collections) . '
'.
  '
' . $this->l("Pearls") . $this->get_pearls_menu($collections_category_link) . '
'.
  '
' . $this->l("Prices") . $this->get_prices_menu($collections_category_link) . '
'.
  '
' . $this->l("Categories") . $this->get_categories_menu() . '
'.
'
';

$this->context->smarty->assign('custom_menu', $custom_menu);

It all goes fine, menu will show up. My problem is with translations: I cannot find them in backoffice to edit. What's wrong with this code?

A: Ok I've just found the solution: strings MUST be delimited with single quotes, not double quotes. So instead of this:
'
' . $this->l("Collections") . $this->get_collections_menu($collections) . '
'

use this:
'
' . $this->l('Collections') . $this->get_collections_menu($collections) . '
'

In other words: $this->('your string') is fine.
Then you'll find the fields to translate on the backoffice translations panel, under the 'module translations' translation type.
And no matter where in the module you'll place the l() functions. Constructor, hooks, string concatenations, everywhere is fine.

A: For translate php
$this->l('Text')

For translate tpl
{l s='Text' mod='Name Module'}

In your case
'
{l s='Collections' mod='Name Module'}'


text:
Q: Hosting Multiple react app in cpanel on singe domain I had delveloped an react application which I want to upload it to cpanel. I had my website also running on the same domain.
Example:
https://www.mywebsite.com host my web content for selling roses.
Now I want to upload my application(APP1) developed in node js as backend and reactjs as front end.
But in future I need to upload similiar other websites too. So I want to create a folder on root and inside or the root i want to upload my application (APP1).
In future if I develop another application(APP2) I want to upload it to same domain in another folder on root (APP2).
My folder structure will be as
Root
   ...WEBSITE FILES
   ...APP1
     ......app1_files
   ...APP2
     ......app2 files
Now how to deploy my APP1 and APP2 on my domain.

A: *

*Go to the 'package.json' file in your React Application, add a package name ("homepage": "YOUR WEBSITE LANDING PAGE LINK")
Screenshot

*Go to the terminal of your editor and type "npm run build".

*Navigate to the Application folder, you will find a folder named "build", upload all the files to the website directory.
HOW TO MAKE A DIRECTORY?

*Go to your cpanel > public_html (this will be your root folder): you can upload your files here.

*If you want to make a directory or another application within the same domain just make a new folder inside public_html and upload the application within that folder and the application will be available by typing: YOURWEBSITE.COM/FOLDERNAME


text:
Q: How do I hide/show DIV element in Razor views? Im trying to complete this very simple task using razor engine (c#+html). Im editing the cshtml file of this view and essentially im trying to achieve this exact code but in "razor" format. Here is what im trying to achieve but in javascript:
HTML:

How many check boxes do you want when clicked on a radio button?

<input type="radio" name="tab" value="igotnone" onclick="show1();" />
None
<input type="radio" name="tab" value="igottwo" onclick="show2();" />
Two

Okay Cool! Here are those two...

<input type="checkbox" value="Yes" name="one">
One
<input type="checkbox" value="Yes" name="two">
Two

JAVASCRIPT:
function show1(){
  document.getElementById('div1').style.display ='none';
}
function show2(){
  document.getElementById('div1').style.display = 'block';
}

What is the code for achieving this exact effect but in cshtml/whatever else is necessary in razor engine?
Total newb when it comes to this front end stuff so I have a second follow up question. I am led to believe that this function needs to go elsewhere like in the "controller" files. Is that necessary or can I insert this method into my cshtml file? Because currently I am editing the already published website through Microsoft Azure's "App preview editor" and it doesn't seem that I can get access to the solution with those files (unless there is o.o)
Thanks!


text:
Q: angular 1 $scope and Controller as, when $scope died? Since when exist "Controller as", it's does not exist since angular 1.2 ? released end of 2013 ? why people , books , blogs and tutorials has written  code with $scope , still in 2015,2014 ?
I've seen people with 1 or 2 years experience using angular 1.1 or angular 1.2 programming style in 2015 and 2016 , they were lost with angular 1.5, for example not using components.
Jobs ask for angular just ask for 'angular programmer' , they know there are big differences people that use every one angular in a different way, by example using $scope, or just directives and  not components, or they dont use ES2015 with babel?
I've never understood that. When really $scope died?
If this question is not for stackoverflow, where i can post it ?

A: Scope hasn't died, and probably will never do so. It's common to think that the controllerAs feature's came to replace scope but it doesn't. Actually, controllerAs comes to deprecate the viewmodel responsibility of scope, when before that, all the viewmodel's members of each template was declared on the component scope, now it's declared on the component's class this, and in the end, it become a member of scope isolating all features of your viewmodel in a single scope member internally.
Using controllerAs to handle your viewmodel is an excelent practice but, you still need scope to do, say, scope things. For example, emit and listen to events, handle disgestion cycle, etc. Therefore, controllerAs comes to separate viewmodel from real scope responsibilities. So, scope never really died at all, just changed how to use it a bit with an optimized feature.
Anyways, it doesn't mean that using old scope way is bad or either using controllers instead of components. Is highly recomended to adopt such practices, in large projects, it makes a lot of more sense than in small ones. Also, old project were built using old angularjs features so, an abrupt change like moving the entire project to the new way as controllerAs and components is not something cheap easy to do, especialy on large projects.


text:
Q: How do I create multiple worlds? I have been searching for a while now for a way to create more than the default, nether, and end worlds to play in.
Example: I want a PvP world, a no-grief world, a grief-allowed world, etc.
Is this possible by any way? I want all worlds to be active at the same time ie. players can be playing on all worlds at the same time.
I would also like to be able to make portals to the world ie. go in them and you warp to the world.
Is this possible by any way? Please don't post such complicated answers as I am not too much of an expert with Bukkit.
Is there any plugin that can support this.
If you have to know, I am using GroupManager for permissions.

A: You want to use Multiverse:

*

*Create multiple worlds of different types, seeds and with Custom Generators

*Create portals to let users go between other portals, worlds, or locations

*PermissionsBukkit support (Anything that implements the superperms api - GroupManager does I think)

*iConomy, BOSEconomy, RealEcon, Essentials Econ and Item economy support!

*Show which users are in what worlds

*Create portals to let users go between worlds

*Control who can enter worlds/portals with permissions!

A: An alternative to Multiverse is My Worlds. I've always found it to be more stable and less lagy. Currently doesn't support 1.5.* but only because BKCommonLib is being slack at updating. I would suggest using Multiverse until BKCommonLib updates and then switch.


text:
Q: Makefile ifeq: when are they evaluated? The following is a very simple makefile that does not seem to work properly.
TEST=ON

buildbegin:
ifeq ($(TEST),ON)
    @echo TEST PASSED
else
    @echo TEST FAILED
endif

No matter what I set the TEST variable to, my ifeq statement passes.  I always see TEST PASSED.  Anyone see what I am doing wrong here?
EDIT:
ok.  my example was not exactly accurate.  What I actually have is this:
SHELL = /bin/sh

DEFAULT_TARGS:= all  all_debug
DEBUG_TARGS:= all_debug
ALL_TARGS:= $(DEFAULT_TARGS) $(DEBUG_TARGS)

.PHONY: $(ALL_TARGS)
.PHONY: buildbegin

$(ALL_TARGS): buildbegin

TEST=ON

$(DEBUG_TARGS): TEST=OFF

buildbegin:
    @echo $(TEST)
ifeq ($(TEST),ON)
    @echo PASSED
else
    @echo FAILED
endif

Running either make all or make all_debug will result in "PASSED" being printed.  If I echo $(TEST) before the condition, it looks as if my rules are changing the variable, but the ifeq only ever sees whatever the default value is.

A: make evaluates conditionals when it reads a makefile (as you know it uses 2 passes), see: Conditional Parts of Makefiles. You can simply check this by using warning (which is good thing to debug makefiles):
buildbegin:
    @echo $(TEST)
$(warning now we reached ifeq TEST=$(TEST))
ifeq ($(TEST),ON)
    @echo PASSED
else
    @echo FAILED
endif

You should use shell commands instead and include them in rule:
buildbegin:
      @if [ "$(TEST)" = "ON" ]; then echo "PASSED"; else echo "FAILED"; fi

A: Here's a cleaner (I think, anyway) way to do what you want:
all:
    $(MAKE) TEST=ON buildbegin

all_debug:
    $(MAKE) TEST=OFF buildbegin

buildbegin:
    @echo $(TEST)
ifeq ($(TEST),ON)
    @echo PASSED
else
    @echo FAILED
endif

A: Parameterise the shell command using make variables. This avoids recursive make and even the shell (make will fork the command directly and not go via a shell if the command contains no shell metacharacters (<>"&; and the like)).
Something like:
result<ON> := PASSED
result<OFF> := FAILED

buildbegin:
    @echo ${result-<${TEST}>}

The <...> is simply a convention to indicate some sort of indirection.

A: Although the question is old, I want to share a simpler way.
It is to use MAKECMDGOALSvariable that represents the list of targets.
In your case, a solution maybe:
buildbegin:
    @echo $(MAKECMDGOALS)
ifeq ($(MAKECMDGOALS),all)
    @echo PASSED
else ifeq ($(MAKECMDGOALS),debug_all)
    @echo FAILED
endif

debug_all: buildbegin

all: buildbegin

Usage: make debug_all or make all


text:
Q: How to request for call logs permission for my android application I am creating an application which performs a certain set of operation for the calls i receive or make.But the application is not able to detect the caller id even though i have provided the required permissions.
My Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />

<intent-filter>
    <action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>

My BrodcastReciever:
  TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
                telephonyManager.listen(new PhoneStateListener(){
                    @Override
                    public void onCallStateChanged(int state, String incomingNumber) {
                        super.onCallStateChanged(state, incomingNumber);
                        System.out.println("incomingNumber : "+incomingNumber);
                        if(state == TelephonyManager.CALL_STATE_IDLE && clientContacts.containsKey(incomingNumber)) {
                            sharedPreferences.edit()
                                    .putString("callerName",clientContacts.get(incomingNumber))
                                    .apply();

                            final Intent intent1 = new Intent(context, ClientInteractionDialogService.class);
                            intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            new Handler().postDelayed(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    ContextCompat.startForegroundService(context, intent1);
                                }
                            },500);
                        }
                    }
                },PhoneStateListener.LISTEN_CALL_STATE);

A: The following code will give you first-time null value but after that, it will always give you the correct number
Take the run time permissions from the user.
For getting phone number in your broadcast receiver you need to implement following code
IncomingCallReceiver.kt
class IncomingCallReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {

        try {
            val newPhoneState = intent!!.getStringExtra(TelephonyManager.EXTRA_STATE)
            val bundle = intent.extras

            if (newPhoneState != null && newPhoneState == TelephonyManager.EXTRA_STATE_RINGING) {
                val phoneNumber = bundle!!.getString(TelephonyManager.EXTRA_INCOMING_NUMBER)

                if (phoneNumber != null) {
                    Toast.makeText(context, "Ring $phoneNumber", Toast.LENGTH_SHORT).show()
                }
             }
       } catch (ee: Exception) {
            Log.i("Telephony receiver", ee.message!!)
        }
    }

}

Register receiver in your manifest file
<receiver
            android:name="com.nip.callblock.IncomingCallReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />

            </intent-filter>
        </receiver>

This will give you the incoming number in onReceive Method
Read this carefully may you will get the solution.
If you found any issue then contact me.


text:
Q: Facebook Live Video and comments Complete novice in this area and hoping you may be able to point me in the right direction. Would love to see samples/examples of code where possible. Wife sells online through FB Live Videos and rather than paying for CommentSold - as it is overkill - we are looking for a way we can 'push' the names of products into Comments of current live video.
In other words, live video is going; we push a button that populates a comment with the name of the next product (the products would be in some sort of list that would be used to populate comment one at a time and as needed). I was thinking Graph API but couldn't find similar examples.


text:
Q: Populate selectize.js field without triggering item_add event How do you selectize.addItem("value") without triggering item_add?

I have a tags field that's dependent on another selection. I need to automatically fill in tags whenever that other selection is changed, and then I need to have a listener run code whenever the user adds or removes a tag. I can't figure out how to add the tags programmatically without triggering the item_add event, but I don't want it triggering before the user's even touched the tags.
(There is addItem(…, silent), but unless I'm mistaken, that only stops it from triggering the change event.)
Sample code:
$('#input-tags').selectize({
  onItemAdd: function() {
    alert("This should only appear by user action");
  }
});
$tags = $('#input-tags')[0].selectize;
$tags.addItem("awesome");
$tags.addItem("neat");

JSFiddle

A: One solution (and the only one I know of) is to remove the event listeners before the addItems and add them back afterwards. That hardly seems ideal, though, especially if it needs to be done more than once.

A: You can convert your code to register the add callback after adding all initial values:
$('#input-tags').selectize();
$tags = $('#input-tags')[0].selectize;
$tags.addItem("awesome");
$tags.addItem("neat");
// Register the listener once you have initialized the selectize component.
$tags.on('item_add', function() {
    alert("This should only appear by user action");
});


text:
Q: EditText/AutoCompleteTextView not observing proper styling when it's in an ActionView I'm trying to style my EditTexts (and AutoCompleteTextViews) a certain way so that the line is a color that I specify.  Normally, this work's just fine by following this answer: How to change the color of the line in ICS styled EditText.
However, it appears as though the style I define for my EditTexts is not observed when the EditText is part of an ActionView in the ActionBar menu.
I.e., I have an action view item in my menu.xml file:
<item
    android:title="Search"
    android:icon="@drawable/search_icon"
    android:showAsAction="always|collapseActionView"
    android:actionLayout="@layout/search_layout"
/>

I specify the layout to be used when this is expanded with the actionLayout property, and then I have a search_layout.xml file that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<EditText
    android:inputType="text"
    android:hint="Enter Search Term"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

This EditText doesn't take on the styling that I've defined in my styles.xml (and the same thing happens if it's an AutoCompleteTextView instead).  How can I customize the style of an EditText/AutoCompleteTextView when it's a part of an ActionView?

A: As William said in the first comment on my question, the solution is to explicitly set the style on the EditText by adding style="@style/YourStyle" to the EditText in search_layout.xml.


text:
Q: Search button not working, it said that no database selected, how to fix this? using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace ICT_Assigment_3
{
    public partial class search : Form
    {
        MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=password");
        MySqlCommand command;
        MySqlDataAdapter adapter;
        DataTable dbdataset;

        public search()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string valueToSearch = search_box.Text.ToString();
            searchData(valueToSearch);
        }

        private void search_box_TextChanged(object sender, EventArgs e)
        {

        }

        private void search_Load(object sender, EventArgs e)
        {
            searchData("");

        }

        public void searchData(string valueToSearch)
        {

            string query = "SELECT * FROM library WHERE add_update('BookName','Publisher','Category','Edition','Year','Location')LIKE'%"+search_box+"%'";
            command = new MySqlCommand(query, connection);
            adapter = new MySqlDataAdapter(command);
            dbdataset = new DataTable();
            adapter.Fill(dbdataset);
            dataGridView1.DataSource = dbdataset;

        }
    }
}

I am new to c#, can someone help me to fix it. I want to search my database, my database have BookName,Publisher, Category,Edition,Year,Location.
I wan to search for all thing, like if i have a book name The Light, R.R is the publisher, fiction category, first edition, 2002 for year and K105 for location in my library.
When i type Light in the text box, it should filter out The Light,R.R....
When i type R.R, it also should show the light, R.R...
Same as category, year, location etc.
i also wan show error if there is no the book in my library
And it is show in data grid view.

A: You need to specify which database to use when establish a connection by adding "database" parameter on your connection string. So, your connection string has to be something like this:
"server=localhost;port=3306;uid=root;pwd=password;database=your_database"

Please see MySQL Connector .NET documentation
Or, you can specify which database to use directly from your query.
SELECT *
FROM your_database.library
WHERE add_update('BookName','Publisher','Category','Edition','Year','Location')
LIKE'%"+search_box+"%'"


text:
Q: Get the division result and group by chanel from two calculated tables sql oracle I have two SELECT statements.
In those statements there is a month, Source and calculating count.
What I'm trying to do is to get the result of a division from these two tables grouped by SOURCE.
And when I do the grouping, I'm getting NULL for the calculation part.
I guess the reason is that going through the months tables are not the same.
For example for the date 201901 there is a source A, but for 201801 there isn't because it didn't exist in that time.
I'm not sure whether I should use JOIN, UNION or anything else.
I know that I'm probably missing something obvious.
Could you please help me with the code?
-- WHAT I'VE ALREADY TRIED
--SELECT *
--FROM t2,t1
--GROUP BY t2.month_id,t1.month_id,t2.PREF_ORDER_SOURCE,t1.PREF_ORDER_SOURCE
--ORDER BY t2.month_id,t1.month_id,t2.PREF_ORDER_SOURCE,t1.PREF_ORDER_SOURCE

WITH t1 as (
SELECT
cust.month_id,
count(*) as AB_P1_TOTAL,
CASE
When CODE='A' then 'AURA'
When CODE='B' then 'SHOP'
When CODE in ('NS','T','CN1','CN2','CO1','CO2','1С') then 'CLUB'
When CODE in ('I','I1', 'I2', 'I3', 'I4', 'I5', 'I6') then 'Internet'
ELSE CODE

end as SOURCE

FROM CUS_T cust
JOIN CUSTOMER dcust ON dcust.month_id=cust.month_id and
dcust.cust_srcid=cust.cust_srcid
WHERE
cust.month_id ='$P-p_ly_parameter'

group by cust.month_id,
CASE
When CODE='A' then 'AURA'
When CODE='B' then 'SHOP'
When CODE in ('NS','T','CN1','CN2','CO1','CO2','1С') then 'CLUB'
When CODE in ('I','I1', 'I2', 'I3', 'I4', 'I5', 'I6') then 'Internet'
ELSE CODE

end

),

t2 as (
SELECT
cust.month_id,
count(*)as AB_P2_TOTAL,
CASE
When CODE='A' then 'AURA'
When CODE='B' then 'SHOP'
When CODE in ('NS','T','CN1','CN2','CO1','CO2','1С') then 'CLUB'
When CODE in ('I','I1', 'I2', 'I3', 'I4', 'I5', 'I6') then 'Internet'
ELSE CODE

end as SOURCE

FROM CUS_T cust
JOIN CUSTOMER dcust ON dcust.month_id=cust.month_id and
dcust.cust_srcid=cust.cust_srcid
WHERE
cust.month_id ='$P-p_current_parameter'

group by

cust.month_id,
CASE
When CODE='A' then 'AURA'
When CODE='B' then 'SHOP'
When CODE in ('NS','T','CN1','CN2','CO1','CO2','1С') then 'CLUB'
When CODE in ('I','I1', 'I2', 'I3', 'I4', 'I5', 'I6') then 'Internet'
ELSE CODE

end
)

SELECT
SOURCE,
1-(t2.AB_P2_TOTAL)/t1.AB_P1_TOTAL

I expect the division grouped by chanel
month_id    SOURCE  Result
201807          Internet  1.15
201807          CLUB      2.12
201808          Internet  3.24
201808          CLUB      4.52

and so on

A: It Depends on what kind of a result you are expecting:
If t1 is 0/NULL, what do you want to do?
If t2 is 0/NULL, what do you want to do?
Depending on the answers to the above question, you can write case statements to get the desired result. I am sorry if this answer did not help. But we would have to clarify the above questions before proceeding.


text:
Q: No errors: But its not indexing faces and not generating the face id's Thank you so much :) Please find the entire code
import boto3
s3_client = boto3.client('s3', aws_access_key_id='xxxxxxxxxxxxx', aws_secret_access_key='xxxxxxxxxxxxxxxxx',)
collectionId='xxxxxxxxx' #collection name
rek_client=boto3.client('rekognition', aws_access_key_id='xxxxxxxxxx', aws_secret_access_key='xxxxxxxxxxxxxxx',)
bucket = 'xxxxxxxxxxx' #S3 bucket name
all_objects = s3_client.list_objects(Bucket =bucket )
for content in all_objects['Contents']:
collection_name, sep, collection_image =content['Key'].parition('/')

if collection_image:
    label = collection_name
    print('indexing: ',label)

    image = content['Key']
    index_response=rek_client.index_faces(CollectionId=collectionId,
                            Image={'S3Object': 'Bucket':bucket,'Name':image}},
                            ExternalImageId=label,
                            MaxFaces=1,
                            QualityFilter="AUTO", DetectionAttributes=['ALL'])

print('FaceId: ',index_response['FaceRecords'][0]['Face']['FaceId'])

A: collection_name,collection_image =content['Key'].split('/')

requires that content['Key'] contain exactly one forward slash (/).
The error indicates that it contains none, so .split('/') just returned the equivalent of doing [content['Key']] (making a list with one element, the entire contents of content['Key']). Thus, you only have one value to unpack, but you tried to unpack to two values, and get the error you see.
You either need to filter out the values that don't meet your requirements, or use a system that guarantees you get the expected number of values, e.g. str.partition:
collection_name, sep, collection_image = content['Key'].partition('/')

With str.partition, if the partition string doesn't occur, then sep and collection_image will be assigned the empty string, "".


text:
Q: Python Click CLI Library - retry input prompt on validation error I'm using the Click library to create a small CLI tool. At a certain point I prompt for a user's e-mail that is validated.
When the validation fails, the tool exits with an error code. Is there an option/functionality/method to let click retry asking a valid e-mail from the user? Could not find any reference to it in the manual.
Actually I want the same behaviour as the password prompt in the below example. When the two entered passwords are not the same, the password has to be re-entered again. Is it possible to enable this for any prompt?
def validate_email(ctx, param, value):
    if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", value):
        raise click.UsageError('Incorrect email address given')
    else:
        return value

@click.command()
@click.option('--email', prompt="E-mail address", callback=validate_email)
@click.option('--password', hide_input=True, confirmation_prompt=True)
def ask_email(email, password):
    click.echo('Valid Email: ' + email)

Thanks!

A: If you catch your exception, you can prompt within the except block and then call your validation callback again (this will recursively loop until a valid entry is given):
def validate_email(ctx, param, value):
    try:
        if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                        value):
            raise ValueError(value)
        else:
            return value
    except ValueError, e:
        click.echo('Incorrect email address given: {}'.format(e))
        value = click.prompt(param.prompt)
        return validate_email(ctx, param, value)


text:
Q: Cordova - IOS webview is moving weird issue.. On Android my webview is static (i.e. I cannot move the app up and down) but on IOS I can move the entire webview up and down (therefore causing the header at the top to move up and down which is a bummer :()
I need the webview to not move up and down so my header doesn't move as the webview does... it works find on Android :(

A: Sombody else asked the question but used correct terminology, the issue is that webviewbounce wasn't disabled for IOS.. https://stackoverflow.com/a/18799560/1332999
Ashis Kumar's (correct but not marked answered) answer:
Try using below one in your config.xml,
If you are using it for Android, then use
<preference name="disallowOverscroll" value="true" />

<preference name="webviewbounce" value="false" />

And for IOS, use like
<preference name="DisallowOverscroll" value="true" />

<preference name="webviewbounce" value="false" />

Hope this helps you.


text:
Q: Dynamic memory allocation without brackets I need to rewrite this code without using brackets.
#include <iostream>

using namespace std;

struct struct_set
{
    unsigned long long number;
    struct_set *next;
};

int main()
{
    struct_set s1[100];
    int a,n=1;
    cin >> a;
    s1[0].number = a;
    s1[0].next = NULL;
    cin >> a;
    while(a!=0)
    {
        s1[n].number = a;
        s1[n-1].next = &(s1[n]);
        cin >> a;
        ++n;
    }
    for(int i = 0; i < n; ++i)
    {
        cout << s1[i].number << " ";
    }
    return 0;
}

I set size of the array s1 to but I don't know this number. In exercise is written: totally random amount which value of number is no more than 2 to the power of 31. I can use iostream, cstdio and stdio.h libraries. No templates.
Does anyone have idea how to do it?
Thanks.

A: I've been persuaded (blame Lounge<C++>) to post an answer that does (at least sort of) answer the question that was asked (how to write the code without brackets), even though it clearly misses the real point.
??=include <map>
??=include <string>
??=include <algorithm>
??=include <iostream>
??=include <iterator>
??=include <limits.h>

class xlat ??<
    std::map<char, std::string> table;
public:
    xlat() ??<
        for (int i = 0; i < UCHAR_MAX; i++)
            table??(i??) = i;
        table??('??='??) = "??" "=";
        table??('??/??/'??) = "??" "/";
        table??('??''??) = "??" "'";
        table??('??('??) = "??" "(";
        table??('??)'??) = "??" ")";
        table??('??!'??) = "??" "!";
        table??('??<'??) = "??" "<";
        table??('??>'??) = "??" ">";
        table??('??-'??) = "??" "-";
    ??>
    std::string operator()(unsigned char in) ??< return table??(in??); ??>
??>;

int main() ??<
    std::cin >> std::noskipws;
    std::transform(std::istream_iterator<char>(std::cin),
        std::istream_iterator<char>(),
        std::ostream_iterator<std::string>(std::cout),
        xlat());
??>

With this, you can write your code normally (using brackets where you see fit) then run it through this program (which works as a filter) to transform all brackets to their trigraph form, so the source code won't include any brackets (or braces). The ugliness you see above is the result of its having been run on its own source code, thus eliminating all brackets and braces.
For anybody who's into language-lawyer tricks, note how I've specified the strings containing the trigraph sequences. To maintain them as strings of three characters, each is written as a pair of adjacent string literals. Trigraph sequences are substituted in phase 1 of translation, but adjacent string literals aren't concatenated until phase 6, so the trigraph sequences aren't produced until after trigraph substitution has taken place.
Note on compiling: Both VC++ and g++ disable trigraph substitution by default. To compile this with those, you need to specify --trigraph with g++, and /Zc:trigraph with VC++.
As to the question originally asked: you normally build a linked list by allocating nodes in the linked list individually. Since you've specified C++ and your restrictions don't seem to elimninate the use of new, that's what you probably want to use. For example, let's build a linked list of some numbers, then print out the contents of the linked list:
struct node {
    unsigned long long number;
    node *next;
    node(unsigned long long n, node *next=nullptr) : number(n), next(next) {}
};

void destroy(node *root) {
    if (root==nullptr)
        return;
    destroy(root->next);
    delete root;
}

int main() {
    node *root = nullptr;

    // build the linked list:
    for (int i=0; i<20; i++)
        root = new node(i, root);

    // print it out:
    for (node *temp = root; temp; temp = temp->next)
        std::cout << temp -> number << "\n";

    // destroy it:
    destroy(root);
}

Notes:

*

*This source code lacks brackets (even without using the preceding monstrosity).

*This uses a "raw" new to allocate each node. For production code you really don't want that, but the "right" approaches would require either writing all the code for a smart pointer on your own, or else violating the restrictions on what headers can be used. At a guess, it would probably also violate your professor's expectations.

A: struct struct_set
{
    unsigned long long number;
    struct_set *next;
};

Is linked list
So there is not any need to write it as contiguous memory.
for more Linked list
As it is homework, do that by yourself

A: You can make a pointer to your structure then allocate memory for 100 element:
struct struct_set *s1;
s1 = (struct_set *)malloc(100*sizeof(struct_set));

You don't need to write &(s1[n]) to get the adress of s1[n]. According to pointers arithmitics s1+n is the adress of s1[n]
    s1[n].number = a;
    s1[n-1].next = (s1+n);


text:
Q: I need to select total hours in one day. first-in and last-out. using SQL query how to code a query with this problem. I need to select total hours within a day. from first-in and Last-out then to sum again The period date_01 to date_16 which is 15days.
[EmployeeID]   [Att_Date]
 01            2022-02-01 07:39:12
 01            2022-02-01 19:39:12
 01            2022-02-02 08:39:12
 01            2022-02-02 19:00:12
 01            2022-02-03 08:00:12
 01            2022-02-03 19:00:12
 02            2022-02-02 08:00:12
 02            2022-02-02 19:39:12... (Raj Marvic)

I tried this code below, but it just only sum result total hours from first-indate to Last-out date, which is its wrong. I need to total daily first, to sum the total hours from first-indate and Last-outDate.
SELECT EmployeeID,
       TIMESTAMPDIFF(hour, MIN(Att_Date),MAX(Att_Date)) AS diff_in_hours
FROM att_details
GROUP BY EmployeeID;

A: I think the reason you are missing your correct total is because the MIN() and MAX() are getting the earliest date/time vs latest date/time which span multiple days.  What I think you are trying to get is the aggregation of EACH DAY, such as totaled over a given week, or multiple day span.  That said, your first query should be grouped by employee AND Date (without time context), THEN sum that result.  One caveat not mentioned... Is it possible for one employee to clock-in/out multiple times in a single day, such as to account for lunch time where that time is excluded from the total work day?  If so, that will need to be accounted for.
select
      EmployeeID,
      Sum( DailyHours ) TotalHours
   from
      ( SELECT
              EmployeeID,
              Date( Att_Date ) SingleDay,
              TIMESTAMPDIFF(hour, MIN(Att_Date),MAX(Att_Date)) AS DailyHours
           FROM
              att_details
           GROUP BY
              EmployeeID,
              Date( Att_Date ) ) PQ
   group by
      EmployeeID

A: Using aggregation along with DATEDIFF we can try:
SELECT
    [Employee ID],
    DATEDIFF(hour, MIN([Date/time]), MAX([Date/time])) AS diff_in_hours
FROM yourTable
GROUP BY
    [Employee ID];


text:
Q: How would one add the fist number of a new array to the array preceding it to obtain the sum total using javascript This is the first time I have asked a question on here so please bear with me.  I am working on a task that has me totaling up a ten-pin bowling scorecard.  Where I am currently hung up is I am trying to add the total of one array to the first number on the next array and I am unsure about how to go about this.
In essence, a portion of the scorecard reads as follows:
[6, 4], [5, 4]

What I am looking to do is obtain the total of the first array (i.e. 10) and then add the first item of the next array to it to give an overall total of 15 which would be the score after a "spare" in bowling.
I have a feeling I would need to be using dot or square bracket notation to achieve this but I am just not sure as I am still pretty fresh to all this.
For reference sake the whole array is as follows:
const frames = [[1, 2], [6, 4], [5, 4], [10, 0], [7, 2], [10, 0], [10, 0], [5, 2], [7, 0], [4, 4]];

Please let me know if there is any more detail I should provide, as I say this is all a bit new to me! Thank you for any pointers in advance.

A: I've left it a bit messy so you can see what's going on.
const frames = [[1, 2],[6, 4],[5, 4],[10, 0],[7, 2],[10, 0],[10, 0],[5, 2],[7, 0],[4, 4],];

const sumArray = frames.map((frame, i) => frame.reduce((curr, acc) => curr + acc) )

for(let i = 1; i < frames.length; i++) {
    frames[i][0] += sumArray[i-1]
}

console.log(frames)
// [ [ 1, 2 ],  [ 9, 4 ],  [ 15, 4 ], [ 19, 0 ],  [ 17, 2 ], [ 19, 0 ,  [ 20, 0 ], [ 15, 2 ],  [ 14, 0 ], [ 11, 4 ] ]

Mutating the array isn't the best but hey.
Oh and I don't know bowling but if you want this to be additive just do this:
for(let i = 1; i < frames.length; i++) {
    frames[i][0] += frames[i - 1].reduce( ( a, c ) => a + c )
}

You'll get
[[ 1, 2 ], [ 9, 4 ], [ 18, 4 ], [ 32, 0 ], [ 39, 2 ], [ 51, 0 ], [ 61, 0], [ 66, 2 ], [ 75, 0 ], [ 79, 4 ]]

A:

const frames = [[1, 2], [6, 4], [5, 4], [10, 0], [7, 2], [10, 0], [10, 0], [5, 2], [7, 0], [4, 4]];

const scores = frames.map((pins, i) => {
  let score = pins[0] + pins[1];
  // You could also use reduce like:
  // let score = pins.reduce((sum, num) => sum + num);

  const next = frames[i + 1];
  if(next) {
    score += next[0];
  }

  return score;
});

const totalScore = scores.reduce((sum, num) => sum + num);

console.log(totalScore);
console.log(scores);


text:
Q: Bounty limit still 100 after deleting answer This question states that if you have answered a question and start a bounty on that question, the minimum bounty is set to 100.
I asked a question, answered it, deleted my answer (because the solution didn't work) and the bounty limit is still 100.
Is this still by design or is this a bug?
If it is by design, then what is the motivation of this? I understand not wanting to hack the bounty system but applying this to deleted questions seems to not fit with that.


text:
Q: i am unable to generate a SHA1 key following the tutorial from udacity So I installed a new JDK version, and then installed android SDK.
the first step of the tutorial require to create a new app in firebase which requires SHA1 key
the tutorial mentions the below to write in cmd

keytool -exportcert -list -v \
  -alias androiddebugkey -keystore %USERPROFILE%.android\debug.keystore

but it returns an error that -exportcert and -list both can't be used together,
So I removed -exportcert by reviewing few answers here that worked for some people but still it didn't work for me.
A work around which I also tried was to double click the certificate file in gradle which showed an error saying missing keystore.
And below is the final error from Cmd after trying many combinations running from C: and from java directory directly
keytool error: java.lang.Exception: Keystore file does not exist:
    C:\Users\fadi\.android\debug.keystore
    java.lang.Exception: Keystore file does not exist: C:\Users\fadi\.android\debug.keystore
    at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:899)
    at java.base/sun.security.tools.keytool.Main.run(Main.java:409)
    at java.base/sun.security.tools.keytool.Main.main(Main.java:402)

A: You need to change directory from
C:\Users\fadi\.android\debug.keystore

to
where your keystore file found


text:
Q: Vim / Neovim Why use autocommands when you have lua functions? I have some experience with vim but most of my time has been spent in neovim playing around with lua (although I'm still barely not a beginner). I missed out on the vimscript autocommand magic that I see alot of people pulling off and I'm wondering why not just write a lua function like...
function OpenTerm()
  vim.cmd("bel split")
  vim.cmd("terminal")
  vim.cmd("setlocal nonumber norelativenumber")
end

instead of writing a an autocmd ?

A: You are conflating two totally unrelated things.
Your snippet (assuming it works, I don't use Neovim  so I won't test it):
function OpenTerm()
  vim.cmd("bel split")
  vim.cmd("terminal")
  vim.cmd("setlocal nonumber norelativenumber")
end

is a Lua function that is exactly equivalent to this Vimscript function:
function! OpenTerm()
  bel split
  terminal
  setlocal nonumber norelativenumber
endfunction

and both functions have literally nothing to do with autocommands. They are completely passive and defining them only did some low-level memory-related things. For them to do anything, you have to call them.
Autocommands are a very different thing that allows you to tell Vim to perform some action when an event occurs, like this one:
autocmd VimEnter * call OpenTerm()

which, essentially, tells Vim this:

When you are done starting up, call the OpenTerm() function.

Unlike functions, which do nothing until they are called, autocommands have a real effect on your editor's state as soon as they are defined.
You can add an autocommand from a function, you can call a function from an autocommand, but you can't expect one to act as the other.
Basically, the question "Do I use an autocommand or a function?" makes no sense at all.


text:
Q: how to have internet access in ubuntu in virtualbox via bridged network? how my laptop is using a wireless network adaptor for internet connection. How may I configure my Ubuntu in virtualbox to have internet access via the wireless network adaptor?

A: Choose bridged network adapter and choose your wifi card. Refresh mac address on that view (it's under advanced options) and it should work. If your host has Internet, virtual box machine should have it also


text:
Q: Solve $(2x - 1)y'' - 4xy' + 4y = 0$ I am self-studying differential equations using MIT's publicly available materials.  One problem set question asks us to first verify that $x$ is a solution to $(2x - 1)y'' - 4xy' + 4y = 0$ (with $2x > 1$) and then use this to find a second, linearly independent solution.
The verification piece, of course, is trivial, but I am stumbling on second part.  I know that, in general, given a solution $f$ of a second order ODE $y'' + p(x)y' + q(x)y = 0$, we can obtain a linearly independent solution $g$ via the formula
\begin{align}
g & = f\int\frac {e^{-P(x)}}{f^2}dx
\end{align}
where
\begin{align}
P(x) = \int p(x)dx.
\end{align}
In this case we have
\begin{align}
P(x) & = -4\int \frac{x}{2x - 1}dx\\
& = -2x + \ln|2x -1|
\end{align}
which means that
\begin{align}
g(x) & = x\int \frac{e^{-2x}}{x^2(2x - 1)}dx
\end{align}
which (at least according to Wolfram Alpha) requires an exponential integral to satisfy.  Indeed, plugging the original DE into Wolfram Alpha leads me to something called a Sturm-Liouville equation, an entity with which I am not (yet) familiar.  (Wolfram gives a different basis of solutions for the ODE as well--but I digress.)
On the other hand, I can see that $e^{2x}$ solves the differential equation--but I kind of stumbled on this fact, rather than using any (non-fuzzy) reasoning to obtain it.
There must be something obvious that I'm missing here--but I don't see it.

A: Here is a full argument. But before: do not memorize unnecessary formulas.
So, you have your solution $y(x)=x$. Noe, look for a solution in the form $y(x)=u(x)x$. You should end up with
$$
u''+\frac{4x-2-4x^2}{2x^2-x}u'=0.
$$
Now, using $v=u'$ you have a separable equation for $v$. You should find that
$$
v(x)=e^{2x}\frac{2x-1}{x^2}\,.
$$
Hence
$$
u(x)=\int v(x)dx=\frac{e^{2x}}{x}+C.
$$
Hence, finally, your second solution is simply
$$
y(x)=u(x)x=e^{2x},
$$
which can be checked by direct substitution.


text:
Q: Cascade algorithm for wavelet and scaling functions It has been described to me that the wavelet and scaling functions can be computed using the Cascade Algorithm applied to the low and high pass filter coefficients.
Where can I find some proofs of how this happens?

A: Some sources that may be useful include:

*

*"Wavelets and Subband Coding" by Martin Vetterli and Jelena Kovacevic, which provides a comprehensive introduction to wavelets and subband coding, including the derivation of wavelet and scaling functions using the Cascade Algorithm.

*"A Wavelet Tour of Signal Processing" by Stephane Mallat, which also provides a detailed introduction to wavelets and subband coding, and includes a proof of how the wavelet and scaling functions can be computed using the Cascade Algorithm.
Research papers on wavelet transforms and subband coding, which can be found through academic databases such as the IEEE Xplore Digital Library or the ACM Digital Library, many of them will provide detailed proofs of the theory behind the wavelet and scaling functions computation.


text:
Q: Why pandas.Series.values drops some scalar data exists in original Series? I have a pandas.Series object docs of which scalar values are string.
when I tries to iterate over docs.values, for example make list(docs), some of the scalar entries are dropped, or become a NoneType.
For instance, given target_index is an index with buggy issue, when I check docs[target_index], it returns a string data. However, when I execute list(docs)[target_index], it returns None.
Since pandas.Series.values turn data into numpy.ndarray, I guess the issue has something to do with numpy data type or something, but I cannot figure out whats going wrong exactly.
Here is the buggy json file of dataframe
https://gist.github.com/goodcheer/f9c990171a57ff053b4b0539396f63f6
docs is the profile column series


text:
Q: Mysql subquery IN clause Find by JSON Value I have two tables.  One is product_details and another one is size.
 Each product have multiple sizes. I have to get set of size for each products.(like 100, 125, 150).  But i already saved the size record as JSON value (like ["1","2","8"]) in product_details table.
 When i try to get the record using IN clause & Subquery, i can't able to get the records.
Check this link: click here sqlfiddle
SELECT po_det.po_det_size as json_str,
REPLACE(REPLACE(REPLACE(po_det.po_det_size, '[',''),']',''),'"','')) str,
(SELECT GROUP_CONCAT(size.size_name)
 FROM tbl_product_size size
 WHERE size.size_id IN (str)
) AS sizes
FROM tbl_purchase_order_details po_det

Please help me to get the records.

A: You can't use in for this.  You can use find_in_set():
where find_in_set(size.size_id, str) > 0

I don't think you can use a column alias in the subquery, so that might be another problem:
where find_in_set(size.size_id, REPLACE(REPLACE(REPLACE(po_det.po_det_size, '[',''),']',''),'"',''))) > 0


text:
Q: how to get date value from the @using (Html.BeginForm( In my razor view I have a simple form that's going to accept a date from user:
@using (Html.BeginForm("CancelByDate", "ClassExample", FormMethod.Post, new { id = "dateForm" }))
   {
      <input id="dateInput" type="date" width="10" class="date" />
      <input type="submit" value="Continue" />
   }

How to get this data in my CancelByDate Action?
I have tried few ways:
    public ActionResult CancelByDate(DateTime dateInput)  // <---- This value will be null
    {
        return View();
    }

    public ActionResult CancelByDate(String dateInput)  // <---- This value will be null
    {
        return View();
    }

    public ActionResult CancelByDate(object dateInput) // <---- This value will be some object, but there is no way to find out what is the underlying type even with GetType();
    {
        return View();
    }

So I am wondering what am I missing?

A: Define a name for date like below
<input id="dateInput" type="date" width="10" class="date" name="dateInput"/>

This name should match with the parameter name in your controller action.
If so the value will be automatically bound.


text:
Q: yarn allocate containers for Spark in AWS I was able to create YARN containers for my spark jobs.
I have come across various blogs and youtube videos to efficiently use --executors-cores (use values from 4 -6 for efficient throughput) and --executor memory after reserving 1 CPU cores and 1GB RAM for hadoop deamons and determined the right values for each executor.
I also came across articles like these.
I am checking how many containers are created by YARN from spark shell and i am not able to understand how the containers are allocated.
For example i have created EMR cluster with 1 master node m5.xlarge (4 vcore , 16 Gib) and 1 core node with instance type c5.2xlarge ( 8 vcore and 16 Gib RAM)
When i create the spark shell with the following command spark-shell --num-executors=6 --executor-cores=5 --conf spark.executor.memoryOverhead=1G --executor-memory 1G --driver-memory 1G
i see that 6 executors including a driver are being created with 5 cores for each executor for a total of 25 cores

However the metrics from hadoop history server does not reflect the right calculations
I am very confused how in spark UI , more cores than available were allocated for each executor . The total vcores in the cluster is 8 cores considering the core nodes but a total of 25 executors are allocated for the executors.
Can someone please explain what i am missing.


text:
Q: iTunes Connect Error: "This email address is not available for use as an Apple ID." When attempting to add a user to iTunes Connect, I get the following error:

This email address is not available for use as an Apple ID. You may already have an Apple ID associated with this address. Please try again or sign in using your existing Apple ID.

This is a different error from the one I usually get, which occurs when trying to add a user with an email address already associated with a different iTunes Connect account.
Why is this error occurring?
How do I fix the issue and invite this user to my iTunes Connect account?

A: Problem

The issue that I found was that the email address was being used as an alternate email on an already existing account.

Solution

Remove the alternate email or change it, then you will be able to use the email for an Apple ID.


text:
Q: JS that reads an XML file, writes HTML code for several divs, then repeats itself until it gets to the end of the list I'd like to update the following page so that it's easier to maintain. http://jsfiddle.net/johanbak/129uq4ts/5/ (Tip: There are panels that contain up to nine squares. Click the gray bars on the left or right to get to the next panel.)
Currently, if I want to add a form, I have to update the HTML and that gets messy. Instead I'd like to maintain an XML file that lists all of my forms. The HTML file would contain a script that writes the HTML code for me based on the contents of the XML.
The HTML has a main div (called panel_wrap). The panel_wrap div contains previous/next navigation divs, and nine square divs (called square). I'd like the javascript to do the following:

*

*Create a panel_wrap div

*Populate the panel_wrap div with the previous/next divs. (I don't mind having to update these independently.)

*Populate the panel_wrap div with nine squares (items 1 through 9 in the XML file).

*Create a new panel_wrap div with a unique id.

*Repeat step 2.

*Repeat step 3, but with items 10 through 19 in the XML file.

*Continue until it reaches the end of the XML file.

The skinny: So basically, I need the script to create a main div, populate that main div with nine other divs (from an XML file), then repeat the process until it reaches the end of the list.
Is that possible?
Here's a sample of what the XML list would look like:
<?xml version="1.0" encoding="UTF-8"?>
<forms>
    <form>
        <name>Form 1</name>
        <subjectCategory>Form1</subjectCategory>
    </form>
    <form>
        <name>Form 2</name>
        <subjectCategory>Form2</subjectCategory>
    </form>
    <form>
        <name>Form 3</name>
        <subjectCategory>Form3</subjectCategory>
    </form> <form>
        <name>Form 4</name>
        <subjectCategory>Form4</subjectCategory>
    </form> <form>
        <name>Form 5</name>
        <subjectCategory>Form5</subjectCategory>
    </form> <form>
        <name>Form 6</name>
        <subjectCategory>Form6</subjectCategory>
    </form> <form>
        <name>Form 7</name>
        <subjectCategory>Form7</subjectCategory>
    </form> <form>
        <name>Form 8</name>
        <subjectCategory>Form8</subjectCategory>
    </form> <form>
        <name>Form 9</name>
        <subjectCategory>Form9</subjectCategory>
    </form> <form>
        <name>Form 10</name>
        <subjectCategory>Form10</subjectCategory>
    </form> <form>
        <name>Form 11</name>
        <subjectCategory>Form11</subjectCategory>
    </form> <form>
        <name>Form 12</name>
        <subjectCategory>Form12</subjectCategory>
    </form> <form>
        <name>Form 13</name>
        <subjectCategory>Form13</subjectCategory>
    </form> <form>
        <name>Form 14</name>
        <subjectCategory>Form14</subjectCategory>
    </form> <form>
        <name>Form 15</name>
        <subjectCategory>Form15</subjectCategory>
    </form> <form>
        <name>Form 16</name>
        <subjectCategory>Form16</subjectCategory>
    </form> <form>
        <name>Form 17</name>
        <subjectCategory>Form17</subjectCategory>
    </form> <form>
        <name>Form 18</name>
        <subjectCategory>Form18</subjectCategory>
    </form> <form>
        <name>Form 19</name>
        <subjectCategory>Form19</subjectCategory>
    </form> <form>
        <name>Form 20</name>
        <subjectCategory>Form20</subjectCategory>
    </form> <form>
        <name>Form 21</name>
        <subjectCategory>Form21</subjectCategory>
    </form> <form>
        <name>Form 22</name>
        <subjectCategory>Form22</subjectCategory>
    </form>
</forms>

Here's a script I started on, but it doesn't create new panel_wrap divs when needed. It just continues through the XML list until it reaches the end. I end up with a bunch of squares in one panel.
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","test.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

var x=xmlDoc.getElementsByTagName("form");
for (i=0;i<x.length;i++)
  {
  document.write("
");
  document.write("
");
  document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "
");
  document.write("
");
  }

Thanks to anyone who can help or point me in the right direction. I'm sorry this is a bit wordy. (I'm certainly a novice to this kind of work, though it's fun!)

A: So, with help from a friend, I accomplished what I needed to do. (Though there's still a bit more tweaking, this gives me the basic structure I needed.)


text:
Q: How can I read the 1st cluster of Volume C of Windows PC by using win32file.BackupRead in Python? What I want to do
I want to directly access and read Volume C of Windows PC and write it as a binary file.
Issues

*

*My script doesn't give any error, but doesn't work as I expect.

*The size of the output file, T:\001.bin, stays 0 even after the process.

*"print(data_buf)" doesn't show anything

My script
# I want to read the first 4096 bytes of Windows's C drive and write it to "T:\001.bin" by this script. But can't,,,,

import win32file
import win32con
import ctypes

target = r"\\.\C:"
output = r"T:\001.bin"

handle = win32file.CreateFile(
    target,
    win32con.GENERIC_READ,
    win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
    None,
    win32con.OPEN_EXISTING,
    win32con.FILE_FLAG_BACKUP_SEMANTICS,
    None
    )

out_handle = win32file.CreateFile(
    output,
    win32con.GENERIC_READ | win32con.GENERIC_WRITE,
    win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
    None,
    win32con.OPEN_EXISTING,
    win32con.FILE_ATTRIBUTE_NORMAL,
    None
    )

bytestoread = 4096
buf = bytearray(b" " * 4096)
ctxt = ctypes.pointer(ctypes.c_int(5))
pntr = ctypes.c_void_p.from_buffer(ctxt).value

bytes_read, data_buf, pointer = win32file.BackupRead(
                    handle,
                    bytestoread,
                    buf,
                    False,
                    True,
                    pntr
                    )

print(data_buf) # This shows nothing, somehow.

win32file.WriteFile(out_handle, data_buf)

win32file.BackupRead(handle, 0, buf, True, True, pntr)
win32file.CloseHandle(handle)
win32file.CloseHandle(out_handle)

Documents I have read
I have been trying to find the solution by modifing the prameters of win32file.BackupRead but I still don't know it. These are the documents I have read so far.

*

*http://timgolden.me.uk/pywin32-docs/win32file__BackupRead_meth.html

*https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-backupread
My Wish
Can anyone show me how to use "BackupRead" correctly in python scripts ?  If so, that would be highly appreciated.


text:
Q: Compound Interest Samantha puts $1000 into a bank account at the beginning of each year, starting in 2010. At the end of each year 4% interest is added to the account.
Find an expression for the amount in the account at the beginning of year n.
My Approach:
After 1st Year,
$$1000(1.04) + 1000$$
After 2nd Year,
$$1000(1.04)^2 + 1000(1.04) + 1000$$
After 3rd Year,
$$1000(1.04)^3 + 1000(1.04)^2 + 1000(1.04) + 1000$$
And therefore,
$$U_n = (1000){\sum_{r = 0}^{n} 1.04^{r}}$$
However, the answer given in my textbook is:
$$U_n = 25000(1.04^n - 1)$$
Where did I go wrong? How can I get the textbook answer?

A: Hint: Both answers are the same.  Use G.P. summation to see that
$$\sum_{r=0}^r 1.04^k = \frac{1.04^{n}-1}{1.04-1}$$

A: Hint:  Look up geometric series.


text:
Q: How to replace segment object length with decorations? In the following TikZ example I would like to replace the usage of snakes with decorations. How can I adjust the segment object length with decorations?
\documentclass[tikz, preview=true]{standalone}

\usetikzlibrary{snakes}
\usetikzlibrary{decorations.pathmorphing}
\tikzstyle{radiowave old}=[snake=waves,
                           segment length=1mm,
                           segment object length=4mm,
                           segment angle=30
                         ]

\tikzstyle{radiowave new}=[decorate,
                       decoration={waves,
                         segment length=1mm,
                         %segment object length=4mm, <- not available
                         angle=30}
                      ]

\begin{document}
  \begin{tikzpicture}
    \draw[radiowave old] (-1,1) to node[left,pos=0] {old} (1,-1);
    \draw[radiowave new] (-1,-1) to node[right,pos=1] {new} (1,1);
\end{tikzpicture}
\end{document}

A: The key is called radius.  I also converted your usage of the deprecated \tikzstyle to the modern \tikzset.
\documentclass[tikz, preview=true]{standalone}
\usetikzlibrary{snakes}
\usetikzlibrary{decorations.pathmorphing}
\tikzset{
  radiowave old/.style={
    snake=waves,
    segment length=1mm,
    segment object length=4mm,
    segment angle=30
  },
  radiowave new/.style={
    decorate,
    decoration={
      waves,
      segment length=1mm,
      radius=4mm,
      angle=30
    }
  }
}
\begin{document}
\begin{tikzpicture}
  \draw[radiowave old] (-1,1) to node[left,pos=0] {old} (1,-1);
  \draw[radiowave new] (-1,-1) to node[right,pos=1] {new} (1,1);
\end{tikzpicture}
\end{document}


text:
Q: Embedding javascript in
A: You'll have to parse that template into your HTML and add click events.
There are two ways to do this, you can either delegate them from the parent element or add them to your element directly.
Not 100% sure what you're trying to achieve but I think its best to add a class to your span and do this:
$(document).ready(function() {
   $('span.fileName').on('click', $.blockUI);
});

If you are rendering this template a lot its better to delegate it from the parent, from jQuery 1.7+ you can use this syntax:
var parentSelector = ''; // YOUR PARENT SELECTOR HERE
$(document).ready(function() {
   $(parentSelector || document).on('click', 'span.fileName', $.blockUI);
});

If you are using older versions of jQuery, use this:
$(document).ready(function() {
   $('span.fileName').live('click', $.blockUI);
});

Delegating simply means binding the handler on the parent to listen for events on specific children.
Also, to make sure the $ sign actually means "jQuery", It is a good practice to put your inline script code in an IIFE
So the first example would look like this:
(function($) {
  $(document).ready(function() {
     $('span.fileName').on('click', $.blockUI);
  });
})(jQuery);


text:
Q: MySQL getting contents from one table that is related by a foreign key from another table I have two tables:
CREATE TABLE users(
    userID int primary key not null auto_increment,
    username varchar(16),
    passcode varchar(16),
    email varchar(50) not null
);

CREATE TABLE favorites(
    userID int not null,
    favID1 varchar(50) not null,
    favID2 varchar(50) not null,
    favID3 varchar(50) not null,
    favID4 varchar(50) not null,
    favID5 varchar(50) not null,
    favID6 varchar(50) not null,
    favID7 varchar(50) not null,
    favID8 varchar(50) not null,
    favID9 varchar(50) not null,
    favID10 varchar(50) not null,
    favID11 varchar(50) not null,
    favID12 varchar(50) not null,
    FOREIGN KEY fk1(userID) REFERENCES users(userID)
);

And I would like to get the contents of the favorites table with just the username from the users table, what would the statement for it look like? I'm fairly new to SQL and databases, so apologies if this is trivial. Every other resource I've looked at doesn't seem to relate to what I want to do.

A: Your database design has some problems.  Instead of maintaining separate columns for each favorite, you should modify the favorites table such that a single record stores one, and only one, user-favorite relationship:
CREATE TABLE favorites (
    userID int not null,
    favID varchar(50) not null,
    FOREIGN KEY fk1(userID) REFERENCES users(userID)
);

Now, if you want to report the favorite IDs for a given user, you need only use a basic join, e.g.
SELECT
    u.userID,
    u.username,
    GROUP_CONCAT(f.favID ORDER BY f.favID) AS favIDs
FROM users u
LEFT JOIN favorites f
    ON u.userID = f.userID
GROUP BY
    u.userID,
    u.username;

Perhaps the biggest problem with your current design of the favorites table is that it only admits up to 12 favorite IDs.  Should your system ever have the need to support more than that, the table itself would have to be modified, i.e. you would need a DDL change.  With my suggested design, you would only need to add more records/data, which is a DML change.


text:
Q: send data struct over network between C/C++ server, C/C++ and C# clients My client will communicate with clients using a struct/class called annoucement. I suppose I will write the server in C++. There will be many different classes that inherit annoucement. My problem is to send these classes over network to a client
I thought maybe I should use iovec. However I don't know if there is anything corresponding to iovec in C#.
The idea is:
I would send a struct with writev, a client would use readv and read the data from the socket like it would be an annoucement class, check uint16 variable in the received struct to deduce the exact type and read the rest of data with apprioprite iovec/readv.
C# can send whole objects as an array but how to interpret it in C/C++?
I want both C/C++ and C# clients to work with the same protocol but that is the first time I designed the protocol and I'm not sure all my ideas will work together.
Any hint'd be appreciated.

A: Don't try to define your protocol in terms of structs.
Define the format of an announcement, i.e. what bytes in what order constitute an announcement, and then define how multiple announcements are transmitted in sequence.
Once you've got this wire format defined, you can implement parsers and writers in each programming language, using the most appropriate programming language constructs, libraries and frameworks available in each.
A good example for this is protobuf: format specification, C++, Java, Python implementation, .NET implementation.

A: The question is a bit chaotic, but I have a feeling that you might be interested in Protocol Buffers for efficiently serializing data and transferring it over the network.

A: There are a number of options when it comes to serialization. This FAQ at parashift.com discusses serialization/deserialization in detail: http://www.parashift.com/c++-faq-lite/serialization.html.