How to make Vuejs watcher react to the watched variable change in a sibling?

Question: I have Search.vue (parent), from where I pass as prop api_url to List.vue (child1), where a watcher of this variable is installed and reloads the list of entities received from API-endpoints every time the user changes filter values (located in parent).
Also I have Post.vue (child2), where the form is located adding one more entity to the DB through API-endpoint.
My goal is to make the whole structure reload list of entities automatically every time "submit" button is pressed in child2.
I tried this in child2:
export default {
    data(){
        return{
            api_url: "",
.......
    methods:{
        submitForm(){
            axios.post('api/v1/houses', this.form)
                 .then((res) => {
                    api_url='api/v1/houses'

but it didn't work out.
Answer: I see two possible ways you can make this work.
First one is to use a state management library like Pinia or Vuex. That would allow you to create global states that can be accessed/changed/watched by any of the 3 components you mentioned, regardless of their hierarchy.
Second option would be to make your parent component (Search.vue) responsible for managing all the data flow and turn your children components into dummy ones -- i.e. they would just receive props from their parents with all the data they need, and emit events to their parents when something important happens. Thus, the child2 (Post.vue) component would emit an event like this.$emit('submitButtonClicked') to the parent. The parent would react to the event by loadin any data needed (calling an API in your case I assume) and provide the data as a prop to child1 (List.vue).
Comment: `provide` and `inject` are something worth looking into. this is the vanilla vue way of handeling shared state without *prop-drilling* (https://vuejs.org/guide/components/provide-inject.html#prop-drilling)


Unable to click link in li tag in selenium

Question: I need to click a link which is inside  and  tag
I tried this but not able to click.
driver.findElement(By.xpath("//div[(@class,'menuRoot')]")).click();

Note : this is inside the frame
below is the html code

Search

Member

Wizards

Establishment

Workflow

Comment: There are so many links which you would like to click? If it is there inside frame then you need to switch to frame first.
Comment: //div[@class='menuRoot'] or //div[contains(@class,'menuRoot')]
Answer: You can click on the menu based on the text present in the menu. Here is some samples,
Search Menu item--
driver.findElement(By.xpath("//a[contains(text(),'Search')]//parent::li")).click();

Member menu item --
driver.findElement(By.xpath("//a[contains(text(),'Member')]//parent::li")).click();

Comment: If i try above xpath getting this error Given xpath expression "//li/a[contains(text(),'Workflow']" is invalid:
Comment: Still getting the same error.      " org.openqa.selenium.ElementNotInteractableException: Element <a class="menu1" href="
Comment: It is a different error. The element identification is working, but interactable. Can you post the full stack trace.?
Comment: 'li' element has onclick method call. you can try click on the li element rather than its anchor element. see updated answer.
Comment: Exception in thread "main" org.openqa.selenium.ElementNotInteractableException: Element  could not be scrolled into view
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'CWQFQV2', ip: '192.168.0.87', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '13'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Comment: driver.findElement(By.xpath("//a[contains(text(),'Search')]//parent::li")).click(); this xpath worked.Thanks a lot
Comment: If it solves the problem, request you to upvote the answer. thanks!
Comment: I have updated.this xpath works driver.findElement(By.xpath("//a[contains(text(),'Search')]//parent::li")).click();


wxPython not finding attributes

Question: I'm at wits end. I am trying to work with Gooey and wxPython with Python 3.9.0 Please find a snippet of my code below.

@Gooey(program_name="My App", required_cols= 3, optional_cols = 2, default_size=(710, 700))
def parse_args():

    parser = GooeyParser(description='Test App)

    parser.add_argument('Names',
                        action='store',
                        widget='FileChooser',
                        help="Upload Your File Containing Names")

    parser.add_argument('Addresses',
                        action='store',
                        widget='FileChooser',
                        help="Upload Your File Containing Addresses")

    args = parser.parse_args()
    return args

args = parse_args()

When trying to run my code on my work laptop, I receive the following error.
File "C:\Users\user\AppData\Roaming\Python\Python39\site-packages\wx\__init__.py", line 12, in <module>
   __version__ = wx.__version__.VERSION_STRING

AttributeError: module 'wx' has no attribute '__version__'

I have navigated to this folder and can indeed see the __version__.py file.
Is there any reason why wxPython would not be able to recognise and import its own attributes? Any help welcomed. I can give more information if needed.
Comment: It's a bit of a hack but if `wx.version()` works in 3.9 python try `wx.__version__ = wx.version().split()[0]` or some variation of it, depending on what is expected.
Comment: unfortunately it does not work in 3.9! For some reason these py modules can not be imported! I appreciate the help though. @RolfofSaxony
Answer: I'm not convinced that:
wx.__version__.VERSION_STRING

would ever work, as wx.__version__ returns a string, as does wx.version()
On Linux:
$ python
Python 3.9.6 (default, Jun 29 2021, 00:00:00)
[GCC 11.1.1 20210531 (Red Hat 11.1.1-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> wx.__version__
'4.0.7'
>>> wx.version().split()
['4.0.7', 'gtk3', '(phoenix)', 'wxWidgets', '3.0.5']
>>> wx.version().split()[0]
'4.0.7'
>>>

If none of the above work, I'd suggest that something is wrong with your installation.
Nothing in your question, offers an explanation as to where the error is generated, as there is no Traceback, so given that pure wx call demonstrably works under python 3.9, the problem could reside in some other module (pafy), that itself utilises wx.
Other than that, I can't be of more help.
Comment: Thanks for the help. I tried simply `import wx` though this gives me the exactly same traceback in my question. It simply informs me there is not attribute called `__version__`. I've tried a reinstallation and still get the same error. I might flag this to the developers

wxPython not finding attributes


Incluir em uma url variavel conunt javascript 'console' chrome

Question: var conta = 1
var conta = 1 + 1
window.open('/teste/numero/11965/', '_blank')
preciso substituir o valor de 11965
pela variavel conta de forma que fique
window.open('/teste/numero/CONTAR/', '_blank')
window.open('/teste/numero/1/', '_blank')
window.open('/teste/numero/2/', '_blank')
window.open('/teste/numero/3/', '_blank')
se tiver como colocar dentro de um loop ou contar 1 to 100000
por gentileza
agradeço.
Answer: Primeiramente, a string que você quer é uma template string, usando ` no lugar de '
ex: window.open(/teste/numero/${suaVariavel}/, '_blank')
o loop ficaria então da seguinte forma:
for (var i = 1; i <= 100000; i++) {
  window.open(`/teste/numero/${suaVariavel}/`, '_blank')
  suaVariavel++
}

Só substituir suaVariavel pelo nome real
Comment: Esther Maia, obrigado funcionando perfeito grato....


Erro DLL Conexão FireDac com PostgreSQL

Question: Estou com o erro de DLL não encontrada ao fazer uma conexão com o PostgreSQL utilizando o componente FireDAC.
Erro:

[FireDAC][Phys][PG]-314. Cannot load vendor library [C:\EXE\libpq.dll]. Hint: check it is in the PATH or application EXE directories, and has x86 bitness.

O detalhe é que já copiei a DLL para o diretório da aplicação, também para teste copiei a dll para o System32 e o Syswow64, porém o erro persiste.
Estou com o Microsoft C++ package 2015 instalado, conforme pede na documentação documentação da embarcadero:
Wiki Embarcadero
Outro teste que realizei foi pelo componente FireDAC tentar realizar a conexão, inclusive no compoente do drive do Postgres apontei a propriedade VendorLib para a DLL, porém, novamente o mesmo erro.
Alguém possui mais alguma sugestão?
Grato desde já.
Comment: Outra informação que possa ajudar: a aplicação foi desenvolvida em plataforma 32bit, sendo assim instalei o postgree x32/x86
Comment: Instala o Postgresql x64 e veja se o problema persiste.
Answer: Para o conhecimento de todos, o problema foi resolvido. Para o PostgreSQL funcionar corretamente é necessário copiar as seguintes DLLs para a pasta da aplicação:

Libeay32.dll
SSLeay32.dll
Intl.dll
Libpq.dll

Copiar essas DLLs do diretório bin da instalação do PostgreSQL.
Comment: x64: `libcrypto-1_1-x64.dll`, `libintl-8.dll`, `libpq.dll`, `libssl-1_1-x64.dll`, `msvcr120.dll`
Answer: Sei q já seu problema foi resolvido, porem gostaria de deixar minha contribuição pra outros..
Recomendo fazer o download dessas dll e colocar na pasta do executável em produção,  na plataforma x86, porque os executáveis por padrão no Delphi é 32bis
no site oficial https://www.postgresql.org/ftp/odbc/versions/dll/
Answer: No meu caso, o problema foi resolvido quando adicionei no Form, o Object Inspector FDPhysPgDriverLink1. Na propriedade VendorHome, vai ter um diretório, apaguei o \lib e pronto.
Funcionou normalmente depois que eu fiz isso.
Answer: No caso, se você quer prototipar sua aplicação em tempo de design, precisa colocar as dlls no diretório do delphi (ver respostas acima, todas estão corretas)
No meu caso, eu copiei as dlls tanto para o diretório do meu projeto quanto para o diretório onde o delphi está instalado
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin
D:\Projetos\Projeto1\Debug\Win32
D:\Projetos\Projeto1\Release\Win32\
eu coloquei as dlls dentro de uma pasta
\Drivers\Pg\x86\
entao ficou assim
C:\Program Files (x86)\Embarcadero\Studio\20.0\bin\Drivers\Pg\x86
D:\Projetos\Projeto1\Debug\Win32\Drivers\Pg\x86
D:\Projetos\Projeto1\Release\Win32\Drivers\Pg\x86\
Eu arrastei um componente PGDriverLib e na property VendorHome eu coloquei "Drivers\Pg\x86"
Funcionou em todos os cenários
Em modo de design
Em modo de debug
Compilado em modo Release
Para distribuir o software copie a mesma pasta Drivers\Pg\x86 para a mesma pasta da aplicacao
Comment: Isto funciona também para outros bancos. MySql é o mesmo procedimento.

Erro DLL Conexão FireDac com PostgreSQL


Custom order the bar of histogram using matplotlib?

Question: I have a graph:

I want the graph xticks' orders to be customized. There are more than 20 graphs to be made from the data. Is there any way I can customize orders of the bar in the histogram with reference to the list.
bar_data=["N/A", "I would probably talk to Yield Advisory", "I would definitely talk to Yield Advisory", "I already use Yield Advisory for this","I might talk to Yield Advisory"]

Answer: If I understand your question correctly, here is the solution https://matplotlib.org/3.1.0/gallery/ticks_and_spines/custom_ticker1.html#sphx-glr-gallery-ticks-and-spines-custom-ticker1-py
You just need to change this piece of code the way you want.
plt.xticks(x, ('Bill', 'Fred', 'Mary', 'Sue'))


How can I select items from my table in to a List?

Question: How can I get the results from my data reader into a List<String>?
Here is my code so far:
public List<string> Item_Getall()
{
    List<string> data = new List<string>();
    SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
    cmd.CommandType = CommandType.StoredProcedure;
    oo.conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        data.Add(rdr["item_name_id_pk"].ToString());
        data.Add(rdr["item_name_arabic"].ToString());
        data.Add(rdr["item_componant"].ToString());
        data.Add(rdr["item_componant_arabic"].ToString());
        data.Add(rdr["item_price"].ToString());
        data.Add(rdr["item_image"].ToString());
        data.Add(rdr["item_category_name_id_fk"].ToString());
    }
    oo.conn.Close();
    return data;
}

Comment: And your question is?
Comment: as a start, use a class for your table.add a property for each column, then use `List` instead of `List`
Comment: As a side note, you should have `using (SqlDataReader rdr = cmd.ExecuteReader()) { //your code }`.
Comment: It looks like you're already doing what you're asking.  Is this not working in some way?  At the very least, you're breaking up each record into multiple entries in the `List<>`, which is certainly odd.  But if this is what you're trying to do, how is it not working for you?
Comment: I hope further clarification
Comment: @PatrickHofman

i selected this method in gridview by using objectDataSourse

the result --> column called "lenght"
i didn't understand !!
Answer: You better use your custom type list instead of string and store your custom type object in list
List<YourCustomType> data = new List<YourCustomType>();

Custom type
public class YourCustom
{
     public string ItemName {get; set;}
     //Similarly all the properties.
}

Reading values from data Reader and adding in Custom Type List
while (rdr.Read())
{
    data.Add(new YourCustom()
    {
       Id = rdr["item_name_id_pk"].ToString(),
       Name = rdr["item_name_arabic"].ToString()
       //Similarly all other properties could be set
    }
}

Comment: A user defined type, public class YourCustom, Give it name which best describes your Entity (Type)
Comment: what's the meaning of " custom type"
Answer: I think you will want to create a custom class and return a list of this class:
public class Item
{
     public int Id { get; set; }
     public string Name { get; set; }
}

Reading would go as:
var data = new List<Item>();
while (rdr.Read())
{
    data.Add(new Item()
    {
        Id = int.Parse(rdr["item_name_id_pk"]),
        Name = rdr["item_name_arabic"].ToString()
    }
}
return data;

Also, look into the using() statement which will make your code more robust in the eye of exceptions during database calls.
Comment: what's the keyword " var "?
what 's it used for !!

var data = new List();
Comment: This is called [type inference](http://joelabrahamsson.com/a-neat-little-type-inference-trick-with-c/). It as the same as writing `List data = new List();`
Comment: ok , thanks
sorry ,but i have anthor question , can you explain " data.Add(new Item()"
Comment: This is called [property initializer](http://msdn.microsoft.com/en-us/library/bb384062.aspx) it is an alternative to providing constructor overloads. It is the same as writing: `var item = new Item(); item.Id = 5; item.Name = "nam"`
Comment: i selected this method by objectdatasource in gridview , but the gridview appeared empty
Comment: In most Grids, you need to add columns and specify which property should be displayed for each column. So in this example you'd have columns for "Id" and "Name". (How it works exactly depends on the Grid - be it a web, winforms, wpf, ... grid)
Comment: http://stackoverflow.com/questions/22788344/i-selected-this-method-by-objectdatasource-in-gridview-but-the-gridview-appear
Comment: coulmns of the table is appeare .. but didn't selected data from database
Answer: Using a DataAdapter and a custom type:
SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
cmd.CommandType = CommandType.StoredProcedure;
oo.conn.Open();

var adapter = new SqlDataAdapter(cmd);

DataTable dt;
adapter.Fill(dt);

oo.Close()

//Convert DataTable to a list of YourType
List<YourType> data = dt.AsEnumerable().Select(s=>
                         new YourType {
                          item_name_id_pk = s.Field<FieldDataType>("item_name_id_pk"),
                          item_name_arabic = s.Field<FieldDataType>("item_name_arabic"),
                             ...
                         })
                         .ToList();

Your custom type would be like;
public class YourType
{
    //Replace the DataType with correct datatype to match with FieldDataType
    public DataType item_name_id_pk {get; set;}
    public DataType item_name_arabic {get; set;}
    ...
}


CakePHP, table $belongsTo two table: error Error: Cannot redeclare table::$belongsTo

Question: I have problem like that - have 3 tables, for example Clients, Hats, Tshirts. Each Client have one Hat and one Tshirt relation. I made this like that:
<code> `
  ClientsModel:
  var $name = 'Client';
  var $belongsTo = 'Hat';
  var $belongsTo = 'Tshirt';

  HatModel:
  var $name = 'Hat';
  var $hasMany = 'Client';

  TshirtModel:
  var $name = 'Tshirt';
  var $hasMany = 'Client';
  `
</code>
I cant display indext.ctp of Clients View, the error is:
        `
       Fatal Error
<code>   Error: Cannot redeclare Cleint::$belongsTo
   File: /var/www/uat/app/Model/Client.php
   `
</code>
How to deal with that relation in my database?
Answer: To declare a belongsTo relation you need to create an array of object not a single var for each belongsTo relation.
In your you client Model the belongsTo relation needs to be like this:
<code>public $belongsTo = array(
    'Hat' => array(
        'className'     => 'Hat',
        'conditions'    => '',
        'order'         => '',
        'foreignKey'    => 'hat_id' //or your external key
    ),
    'Tshirt' => array(
        'className'     => 'Tshirt',
        'conditions'    => '',
        'order'         => '',
        'foreignKey'    => 'tshirt_id' //or your external key
    )
);
</code>
MANUAL
Comment: Thank You!!!!! I have change that, and it works perfectly!!
but have next problem:
      `
       .../cakephp/Clients/add is not working for 100%.
       `

My drop down list in add.ctp is not diplay Hats names, but only number, 1, 2, 3...etc. Why?
Comment: It depends of your code to find values. accept this answer and open another with the new problem :) @tomas3man
Comment: Ok i will open new question now to show the problem.


How do I calculate the total of a shopping cart?

Question: I have the following cart implemented by a custom module I wrote.

The columns are stored in 2 associative arrays.
$jcartItemQty = $_POST['jcartItemQty'];
$jcartItemPrice = $_POST['jcartItemPrice'];

This is what those array could contain:

     [jcartItemQty] => Array
            (
                [0] => 3
                [1] => 1
            )

        [jcartItemName] => Array
            (
                [0] => Armas Jarnefelt - LAULAJAN KOTI
                [1] => Jean Sibelius - Kullervo
            )

        [jcartItemPrice] => Array
            (
                [0] => 110
                [1] => 120
            )

I need to combine somehow the arrays into one that looks like $combined = (3 => 110, 1 => 120) in order to be able to calculate the total.
array_merge() is not working because will only concatenate those 2 arrays.
foreach ($combined as $key => $item) {
  $total += $key * $item;
}

I need to display the total in a form item like this:
foreach ($jcartItemPrice as $key => $value) {
  $form['jcartItemPrice'][$key] = array(
    '#type' => 'textfield',
    '#value' => isset($value) ? $value : '',
  );
}

$form['total'][$key] = array(
  '#type' => 'textfield',
  '#value' => isset($value) ? $value : '',
);

Is there a way to do this?
Answer: You can use array_merge() to merge two arrays into one.
It looks like you're trying to overengineer things. This is a simple solution:
$combined = array();
for ($i = 0; $i < count($jcartItemQty); $i++) {
  $combined[] = array($jcartItemQty[$i], $jcartItemPrice[$i]);
}

Comment: Thank you Florian, nice way to pair 2 matrices. I will keep in my code snippets. Clive has a nice solution to calculate without pair it so I think we both overengineered it :) - it was my idea to pair up things :))
Answer: Assuming the array keys of each array will always match (and that is what you're using to tie the two arrays together):
$total = 0;
foreach ($jcartItemPrice as $key => $price) {
  $total += $price * $jcartItemQty[$key];
}


Integral of the sequence of functions diverge imply supreme of the function is not integrable

Question: Let $(X,\mathscr{M},\mu)$ be a measure space and consider a sequence of non-negative measurable
functions $f_n$ convergent to zero in measure and such that the sequence $a_n := \int f_n$ does not
converge to zero. Prove that the function $g(x) = sup_n f_n(x)$ is not Lebesgue integrable
Answer: If $g$ is integrable, then, because $|f_n| \leq |g|$, the dominated convergence theorem implies that
$$\int f_n d\mu \to 0,$$
which is a contradiction.


how to pre-select a dropdown options which are dynamically generating?

Question: I am getting the select dropdown options from the server, and i have stored a value in a variable in javascript. If the options are matching to the value i am having that will be preselected in the select dropdown. Below is my code.

this is to get the dropdown options from server and append to select dropdown.

$.ajax({
        type: "GET",
        url: '/enquiry/user',
         dataSrc: "data",
         dataType : 'json',
        cache: false,
        success: function(users){
            var mySelect = $('#assigned');
    $.each(users, function(index, options){
      console.log(options._id);
       mySelect.append(
    $('<option></option>').val(options._id).html(options.firstName)
);
        // $('#assigned').append('<option value="'+users._id+'">'+users.firstName+'</option>');
    });

and here i am having a value in a variablef8 = document.getElementById('assigned');

If the value in f8 matches to the options, that option should get pre-selected.

Iam using materialize CSS

Html dropdown
<select id="assigned">
<option value="">Change Assignee</option>
</select>
Comment: `mySelect.val('whatever')` to set select value using jquery
Comment: $("#assigned").val(f8); just add dropdown name and in val write variable name
Comment: Thanks for your quick response, @GSB , this line "$("#assigned").val(f8);" should be written after my ajax call? right!
Comment: @Manoj yes after ajax call you need to call
Comment: @GSB I added but its not working
Comment: @Manoj IN the Ajax Success After the finish of Append Each
Comment: @Manoj your variable value you are retrieving in this format right? f8 = document.getElementById('assigned'); if yes so please call your ajax in $(document).ready(function() {
$.ajax({//coded here});  $("#assigned").val(f8);});
Answer: $('#optionID').prop('selected',true)

//to update material select component per materializecss doc
$('#select').material_select('destroy')
$('#select').material_select()

working fiddle here, though not ajax request, but dynamically generated options
edit:
$('#select').append($('<option></option>').val(VALUE).html(HTML))
$('#select').val(SELECTED_VALUE)
$('#select').material_select('destroy')
$('#select').material_select()

Comment: i gave id to my options like this,is this the right way "$('').val(options.firstName).id(options.firstName).html(options.firstName)"
Comment: it sort of also works, check the updated code... though admittedly, it is behaving a little strangely. edit: working fiddle https://jsfiddle.net/ayetx8o3/


Upload some images to website

Question: I need something like a window browse popup to select some images to upload to my website, how can i do that?
I already googled sometimes but found no answer to this one.
Comment: In case of asp.net use **FileUpload** control
Answer: You can use <input type="file" multiple /> or Jquery

Upload some images to website


Pulling to server remotely from GitHub, remotely

Question: I want to setup a deployment workflow from GitHub to my Digital Ocean server. To do this I don't want to have to login to the server and manually run git pull from my server's repository.
I'm aware of git hooks, and have even used them between my local machine and my server, but I wanted a way to deploy from GitHub to the server so I can guarantee parity between the GitHub repo and the server's repo.
There is very little documentation on how to do this to a non-supported host company (Digital Ocean), so I figured that one way to do it remotely would be to:

Setup a user on my server.
Create an SSH key pair for that user
Add the user's public key as a Deployment Key on my Github repository
Then when I wanted to deploy using my local computer, I would simply send a single bash command (something like cd /var/www/my-repo && git pull) over ssh to the server

The problem is that it seems I can only get as far as point 3. In order to clone/pull the repository from GitHub, I need to start the ssh-agent in my shell. Without doing this my server's user can't pull from GitHub.
An obvious solution might be to simply send the eval `ssh-agent -s` command over the wire along with my cd and git pull commands. However, with a bit of experimenting I realised that the ssh-agents weren't being killed when I killed my shell session with the server. This would mean I would be starting up dormant ssh-agent processes each time I wanted to deploy.
My question is two-fold:

Is this an awful way to deploy (for a pretty low-key site)?
Is there a nice, clean bash script that can start and kill an ssh-agent with every execution?

My server is a Debian server.
Comment: Where do the SSH key files live and why do you need `ssh-agent` running to use them?
Comment: @thrig I don't *know* that I need `ssh-agent` to run them, but I deduced that I did because I was only able to clone my (private) GitHub repo to my server after running ``eval `ssh -s` ``. Or rather, attempts to `ssh-add` my key didn't work and errored with a `Could not open a connection to your authentication agent.`. Not until I had run an ssh-agent and added my key, could I authenticate with GitHub and clone (or pull) my repository. The key files live in the `~/.ssh` folder of the user.
Comment: On the server? Because for github I set a `IdentityFile ~/.ssh/id_github` entry in my `~/.ssh/config` file to use that key for github under the `Host github.com` block.
Comment: @thrig Yes, on the server. I don't know ssh that well, so you'll have to explain the reasons why you think your solution will work. Are you saying that in order to have my server authenticate with GitHub, I need to alter my ssh config to explicitly tell GitHub which key to use? What does the `IdentityFile` directive actually do? I figured that simply having the public key added on GitHub and having the private key existing within my `~/.ssh` folder would do. Am I wrong? P.S Thanks for any help
Comment: 1. you can (and must, really) correctly deploy over SSH **without** SSH-agent 2. Place your generated ssh-key in correct location 3. Read https://gist.github.com/oodavid/1809044 for ideas
Answer: In the end I did two things to successfully authenticate with GitHub:
1) Created an SSH key that did not have a passphrase, and used its .pub as Deploy Key on GitHub repository
2) Made sure that the key was being used when connecting by adding the following to ~/.ssh/config:

host github.com
 HostName github.com
 IdentityFile ~/.ssh/my-rsa
 User git


Disable Browsing With 7-Zip

Question: We have a lot of servers running Windows 2008 r2 (RDS/Citrix). We try our best to lock down remote desktop and published applications.
Recently, one of my colleague showed me how he could use 7-zip to browse our network (with a simple user account). Actually, this is something that i never though we could use to do (I rarely check "little" app like that and put all my effort on "more important apps" like Office Suite, SQL client, etc.).
After checking again, it appears that users connecting to their remote desktop can use 7-zip to browse the network and access files and folders on servers. Fortunately, they can't open files, remove or move them but still I want to find a way to disable this.
I didn't find many docs or manuals for this purpose and since I cannot disable this functionality with GPO (I wish we could keep 7-Zip and not user another apps) could anyone provide me with some help?
Comment: This **can't** be just a 7-zip issue. 7-zip **can't** overrule Windows permission settings. If they can browse the network with 7-zip they can also browse the network with Notepad or windows Explorer for example. If they type `\\servername` in the address-bar they can browse the same way as 7-zip. If this is not wanted you need to set the permissions like the others say.
Comment: Have you tried simply setting permissions to deny access to folders?
Comment: @user3146708 Did you remove the folder traverse permission (assuming NTFS) too? Because filesystem permissions set properly would prevent *any* application from accessing them. Attempting to block this at the application level (7-zip itself) is bad practice.
Comment: Hello Synetech. Already done that and it doesn't work. Still able to browse the network (can't delete files or folders but I can see every thing).
Comment: The only way to disable this is to use domain permissions and prevent them from browsing the folders in the first place.  Being able to view the contents of a folder and being able to read the file are seperate permissions in Windows.  If you feel your permissions are where you want them, you might have to not allow 7-zip, in the end unless the contents of these folders can actually be opened there might not be a great deal you can do about it ( if you still want to allow 7-zip ).
Comment: I agree with you that we shouldn't manage this at the application level and should concentrate on the server side. Tomorrow I will check all permissions again and see if I might have forgotten something.Thanks for your help guyz.
Comment: Notepad, Windows Explorer and other Windows apps are restricred by Group policies. But 7-zip isn't. Though it's not a 7-zip only issue.
Answer: Sounds like you just need to set up Access-based Enumeration.
Access-based enumeration displays only the files and folders that a user has permissions to access. If a user does not have Read (or equivalent) permissions for a folder, Windows hides the folder from the user's view. This feature is active only when viewing files and folders in a shared folder; it is not active when viewing files and folders in the local file system.
Here is a Technet article that goes into some detail.

Disable Browsing With 7-Zip


Se eu retornar algo dentro de um using, os recursos serão liberados?

Question: Eu sei que o using é utilizado para liberar (dar um dispose) recursos. A minha dúvida é no seguinte caso:
public void FuncNaoFazNada()
{
    using(var acd = new AlgumaClasseIDisposable())
    {
        return;
    }
}

Nesse caso, os recursos utilizados por acd serão dispensados? Ou a quebra de fluxo manterá os recursos alocados?
Comment: Relacionada(duplicata?) com [Qual a utilidade do using?](http://pt.stackoverflow.com/q/66230/2541)
Answer: Sim, é um syntax-sugar com funcionamento exatamente igual ao try-finally:
var acd = new AlgumaClasseIDisposable();
try
{
    return FazAlgumaCoisa(acd);
}
finally
{
    acd.Dispose();
}

Answer: A resposta é: será liberado sim.
o using no C# é um açúcar sintático, que nada mais é que um try ... finally no final, onde este seu código:
public void FuncNaoFazNada()
{
    using(var acd = new AlgumaClasseIDisposable())
    {
        return;
    }
}

Será na verdade:
public void FuncNaoFazNada()
{
    var acd = new AlgumaClasseIDisposable();
    try{
        return;
    }
    finally{
        acd.Dispose();
    }
}

Então apesar do return dentro do try, ele vai sempre executar o bloco de código do finally.

Dica: Para entender melhor o funcionamento implemente a segunda forma do código e o debug linha a linha. Assim entenderá como é o fluxo de execução.


Calculate YTD, Previous YTD in the same query

Question: How could I calculate to calculate YTD and prior YTD in the same query?
I try to calculate weight and weight ytd. I didn't undestand how to add the calculation of prior ytd in the same query.

YTD: Sum Weight  from the first of January to today
prior YTD: Sum
Weight from the first of January of last year  to today minus 1 year

SELECT SUM(CASE
                   WHEN convert(date,s.Delivery_Year+'-'+ s.Delivery_month+'-'+ s.Delivery_day) BETWEEN dateadd(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND GETDATE() THEN s.Weight
                   ELSE 0
               END) AS WeightYTD ,
           sum(Weight) AS weight ,
           [Sales_Organization] ,
           [Market_Grp] ,
           [Delivery_Year] ,
           [Delivery_month] ,
           Delivery_day
    FROM Fact_sales s
    GROUP BY ,
                      [Sales_Organization] ,
                      [Market_Grp] ,
                      [Delivery_Year] ,
                      [Delivery_month] ,
                      Delivery_day

Comment: Then please edit your question, to update it with details that cover the full range of behaviours you would like.
Comment: You're selecting all data for all dates, and then grouping by year, month and date.  So, your output results will include rows for last year as well as this year.  What should rows from last year have in their year to date column?  *(For example, taking today's date, `20th March 2019`, you'll also have an output row for `21st March 2018`, should that row's year to date column show 2019's year to date values?)*
Comment: @MatBailie no  it should'nt
Answer: It's still quite unclear as to what results/behaviour you actually want.
One possible interpretation is that the "year to date" is relative to the date in the table, and not relative to "today" / GETDATE().
So...

for 14th March 2018 : YTD = 1st Jan 2018 to 14th March 2018
for 20th March 2019 : YTD = 1st Jan 2019 to 20th March 2019

That being the case, I would do the following to get the YTD column...
WITH
    grouped_by_date AS
(
    SELECT
        [Sales_Organization],
        [Market_Grp],
        [Delivery_Year],
        [Delivery_Month],
        [Delivery_Day],
        SUM([Weight])             AS Weight
    FROM
        Fact_sales s
    GROUP BY
        [Sales_Organization],
        [Market_Grp],
        [Delivery_Year],
        [Delivery_Month],
        [Delivery_Day]
),
    cumulative_sum_for_ytd AS
(
    SELECT
        *,
        SUM([Weight]) OVER (PARTITION BY [Delivery_Year]
                                ORDER BY [Delivery_Month], [Delivery_Day]
                           )
                              AS Weight_YTD
    FROM
        grouped_by_date
),

There isn't a LAG() function in SQL Server 2008, but there are "hacky tricks" that can simulate it...
    hack_to_do_lag AS
(
    SELECT
        *,
        CASE
            WHEN [Delivery_Year]%2=1
            THEN MAX(CASE WHEN [Delivery_Year]%2=0 THEN [Weight_YTD] END) OVER (PARTITION BY ([Delivery_Year]+0)/2)
            ELSE MAX(CASE WHEN [Delivery_Year]%2=1 THEN [Weight_YTD] END) OVER (PARTITION BY ([Delivery_Year]+1)/2)
        END
            AS Weight_PreviousYTD
    FROM
        cumulative_sum_for_ytd
)
SELECT
    *
FROM
    hack_to_do_lag

Comment: this part of code throws error  SUM([Weight]) OVER (PARTITION BY [Delivery_Year]
                                    ORDER BY [Delivery_Month], [Delivery_Day]-----this part
                               )
                                  AS Weight_YTD
Comment: @testtest 1). You changed the code, so your question doesn't reflect how you're testing it.  2). You didn't include the error message.  `Please update your question with the exact code you tested and the exact error message you received.`
Comment: Msg 102, Level 15, State 1, Line 26
Incorrect syntax near 'order'.
Comment: @testtest `Please update your question with the exact code you tested `
Comment: this part of your code throws error SUM([Weight]) OVER (PARTITION BY [Delivery_Year] ORDER BY [Delivery_Month], [Delivery_Day]-----this part ) AS Weight_YTD ----------- Msg 102, Level 15, State 1, Line 26 Incorrect syntax near 'order'.
Comment: @testtest - Please update YOUR QUESTION (not a comment) with the EXACT (as in, full, complete, and not just one line) code that you tested.
Comment: I test exactly your script. It sems that I have a problem with compatibility
Comment: this my version: Microsoft SQL Server 2008 R2 (SP3) - 10.50.6220.0 (X64)   Mar 19 2015 12:32:14   Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 6.3  (Build 9600: ) (Hypervisor)


somar valores em uma lista de objetos Java

Question: Eu recebo uma lista de carros com ano, modelo, fabricante e preço, eu pego essa lista e faço um agrupamento baseado no fabricante, depois eu faço a soma dos preços de todos os carros desse fabricante.
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testes;

/**
 *
 * @author natanael
 */

import modelo.Carro;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Testes {

    /**
     * @param args the command line arguments
     */
    private Double totalPreco = 0.0;
    private Carro carroUm;
    private Carro carroDois;
    private Carro carroTres;
    private Carro carroQuatro;

    private List<Carro> carros = new ArrayList<>();
    private List<Carro> teslaList = new ArrayList<>();

    public static void main(String[] args) {
        Testes test = new Testes();
        test.start();

    }

    public void start(){
        carroUm = new Carro();
        carroUm.setAno("2017");
        carroUm.setFabricante("renalt");
        carroUm.setModelo("sandero");
        carroUm.setPreco(42000.0);

        carroDois = new Carro();
        carroDois.setAno("2020");
        carroDois.setFabricante("tesla");
        carroDois.setModelo("model s");
        carroDois.setPreco(150000.0);

        carroTres = new Carro();
        carroTres.setAno("2020");
        carroTres.setFabricante("chevrolet");
        carroTres.setModelo("onix");
        carroTres.setPreco(57000.0);

        carroQuatro = new Carro();
        carroQuatro.setAno("2021");
        carroQuatro.setFabricante("tesla");
        carroQuatro.setModelo("model x");
        carroQuatro.setPreco(600000.0);

        carros.add(carroUm);
        carros.add(carroDois);
        carros.add(carroTres);
        carros.add(carroQuatro);

        //teslaList = carros.stream().filter(carro -> carro.getMarca().equals("tesla")).collect(Collectors.toList());

        System.out.println(somarValoresList(carros, "tesla", totalPreco));
    }

    public String somarValoresList(List<Carro> lista, String tag,Double valor ){
        lista = carros.stream().filter(carro -> carro.getFabricante().equals(tag)).collect(Collectors.toList());

        for(int i = 0; i < lista.size(); i++){
            valor = valor + lista.get(i).getPreco();
        }

        return valor.toString();
    }

}

meu objeto carro:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo;

/**
 *
 * @author natanael
 */
public class Carro {

    private static String ano;
    private String modelo;
    private String fabricante;
    private Double preco;

    public Carro() {

    }

    public String getAno() {
        return ano;
    }

    public void setAno(String ano) {
        this.ano = ano;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public String getFabricante() {
        return fabricante;
    }

    public void setFabricante(String marca) {
        this.fabricante = marca;
    }

    public Double getPreco() {
        return preco;
    }

    public void setPreco(Double preco) {
        this.preco = preco;
    }

    @Override
    public String toString(){
        return getClass().getSimpleName() + "{marca: "+ fabricante + ", modelo: " + modelo +", ano: "+ ano + ", preço:" + preco + "}";
    }

}

Teria uma forma mais simples ou mais performático de fazer isso em java para que eu não tenha que repetir a mesma linha de código pra todos os fabricantes?
Answer: Quanto a "mais performático" eu não sei te dizer, mas, mais simples dá pra fazer usando o método Collectors.groupingBy.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
  public static void main(String... args) {
    List<Carro> carros = new ArrayList<>();

    carros.add(new Carro("Tesla", "Model X", 600_000.0));
    carros.add(new Carro("Chevrolet", "Onix", 57_000.0));
    carros.add(new Carro("Tesla", "Model S", 150_000.0));
    carros.add(new Carro("Renalt", "Sandero", 42_000.0));

    Map<String, Double> precoTotalPorFabricando = carros
      .stream()
      .collect(
        Collectors.groupingBy(
          Carro::getFabricante,
          Collectors.summingDouble(Carro::getPreco)
        )
      );

    precoTotalPorFabricando.forEach((k, v) -> System.out.printf("%s: %s\n", k, v));
  }
}

class Carro {
  private String fabricante;
  private String modelo;
  private double preco;

  Carro(String fabricante, String modelo, double preco) {
    this.fabricante = fabricante;
    this.modelo = modelo;
    this.preco = preco;
  }

  String getFabricante() {
    return this.fabricante;
  }

  String getModelo() {
    return this.modelo;
  }

  double getPreco() {
    return this.preco;
  }
}

Obs.: Consegui executar seu código de boa, mas preferi reescrever sua classe para o exemplo completo ficar mais limpo.
Edit: E com Collectors.summarizingDouble vc tem ainda mais informações de uma só vez como quantidade, preço mínimo, máximo e média.
Map<String, DoubleSummaryStatistics> precoTotalPorFabricando = carros
  .stream()
  .collect(
    Collectors.groupingBy(
      Carro::getFabricante,
      Collectors.summarizingDouble(Carro::getPreco)
    )
  );


Redirect to a content page after login only from that page

Question: On one certain page of my site, users have to log in before going any further. They don't have to be logged in to see most of the rest of the site content, but on this one specific page, they do have to be logged in. I figured out how to put a barrier up that forces users to log in before seeing that page's content (i.e., if users aren't logged in, the only thing on the entire page is a line that says "To create content, you must first log in" and there's a link to the login page), but how do I redirect newly logged-in users directly back to that same page (which now will have content on it) so they can now see its content?
At the moment, after they log in, it just takes them to their profile page.
In other words, if users log in on any other page, it's fine if they're redirected to their profile page, but on this one specific page, they need to stay put. I've seen lots of variation of the following code:
function hook_user_login(&$edit, $account) {
drupal_goto('node/1');
}

But I don't think this is what I'm trying to accomplish. The current code I have in there looks like this:
$sample1 = 'log in.';
$sample2 = 'To create a classified ad, you must' . " " . $sample1;

global $user;
if ($user->uid == false){
return $sample2;

}

I've seen some code like this that looks promising:
#action' => url($_GET['q'], array('query' => drupal_get_destination()))

But I can't figure out how to make it work. Anyone got any ideas?
Comment: If you don't mind to use [rules module](https://drupal.org/project/rules), take a look at this [answer](http://drupal.stackexchange.com/a/80404/16739) - It's exactly what you're looking for, I think.
Answer: Hope this will give you,
In Drupal 7, you can achieve it by using destination parameter.
Just add the destination parameter in the URL where you want to redirect it.
For example if you are in login page and after login if he want to redirect to some node say about page then

YOUR_DOMAIN/user/login?destination=about

Just add the destination parameter in "To create content, you must first log in" link. On click of this link it will redirect to User login page with the destination parameter. After login it will redirect to the path you have specified in the destination value.
Comment: This worked! Thanks, inzio. However, URLs with equals signs and question marks in them always worry me -- using destination parameters doesn't open me up to SQL injection attacks, does it?
Comment: **SQL injection** is a technique used to take advantage of **non-validated input** vulnerabilities to pass SQL commands through a Web application for execution by a backend database. As we are not executing any **backend database**, we are just redirecting to the particular URL. So no worries :)
Comment: Awesome, thanks for that explanation. That makes sense. I appreciate your help very much.
Comment: Your welcome :)
Answer: Use the r4032login module and it will redirect users to the login page anytime they hit a page that they don't have permission to access.  Once they login it will redirect them back to the page they were trying to access.
Answer: You can use the Rules
module in Drupal. Use something like a 'execute custom PHP code' where you can use request_uri to preg_match with the page you need identified. That's it. Below is a simple block you could use:
$request_url = $_SERVER['REQUEST_URI'];
if (preg_match("/content-page/", $request_url)) {
  return TRUE;
}

Keep the event "User has logged in".
In the condition, "execute custom PHP code"
Create a page redirect below that option to redirect to that page
Assign a greater weight to this Rule if there's already login-redirect rules on your site.

Should get you working.
Answer: This can be achieved by using a combination of content access and login toboggan modules. You'll be able to restrict pages and prompt user to login to access them.


Having a hover or mouseover effect in views for drupal 7

Question: I am creating a staff page for a project, and I am putting an image (suing views) that links to the staff members page.  What I thought would be really cool is if when you scrolled your mouse over the image it turned into the name of the person.  I am not sure at all how to do this, and after several hours of searching I need some help.
Thanks in advance.
Comment: plz expand details.
Answer: You can do a simple thing like this:
HTML

   John Doe

CSS
a.person {
    border: 1px solid #ddd;
    display: block;
    height: 100px;
    overflow: hidden;
    width: 100px;
}
a.person:hover img {
    display: none;
}
a.person span {
    display: block;
    text-align: center;
    margin: 20% 0 0;
}

Fiddle:
http://jsfiddle.net/fXnmr/
If you want fade effects etc you need to go the Javascript/jQuery route.
Answer: If you're using views I'd overwrite the image field with the code by enzipher but use tokens for the staff names so it's pulled from a 'Staff Name' field. Then use CSS and JS to do the rest of the fancy stuff.
So...
Edit your content type to add 'Staff Name' and 'Staff Image'
Create a view of fields
Add 'Staff Name' and 'Staff Image'
Don't display Staff Name and put it above the image in the order
Rewrite Results the Staff Image using the code above and replacement patterns for the staff name and image.
If you want to link this to content don't click "Link to Content" or anything like that. Add the NID field to the mix above, exclude from display then write that into the link.
Or something along those lines.
Hope that helps, i've just done battle with a similar thing that looks like the pic attached...
Good luck!!
Answer: You could do the following.
Add the name as well as the image in the view.
Using css initially place the name below the image covering it completely.
Now again using css write a hover on image and set the display to none so that it would hide and the name would show up.
If you want some kind of animation effects the you would go with JS


I still don't understand the explanation about How does one play music when both hands are to play the same notes?]

Question: [
I've read the previous posts on how to do this and don't understand in this situation how to play them when both hands are to play the same note. Please help by explaining very simply
Comment: Could you please add the source of this piece?
Comment: What instrument(s) is this music for? Are both clefs supposed to be for the same instrument?
Comment: @Dekkadeci - isn't that why there's a bracket holding both parts together? It's surely piano.
Answer: Well, the easy way of course is to play this on an instrument with two manuals, like an organ or harpsichord or free bass accordion or bandonion.
The next "easiest" way on a piano is to play this two-handed (staggering the hands a bit so that the right hand may move across the left hand), use a pedal on each beat and only strike the left hand notes briefly into the pedal in order to be able to play the right hand phrases with the right hand.
Without pedalling, you can do a "left-hand pedal" by releasing the keys not far enough for the notes to dampen but far enough that you may restrike with the right hand.
Playing this right-hand only on the accordion (definitely nicer to use a chromatic button accordion here to avoid stretches) is what I find most mentally draining: basically you think of holding the "left-hand" notes steady but give them a very brief respite when the "right-hand" notes walk across them.  In this case the same fingers are getting used but the melody articulation "walks across them".
That kind of mess happens sometimes in Bach keyboard fugues: where you have just a single manual available for multiple voices, you may have a non-rigid voice distribution across hands and fingers.  You then need to think more in terms of what the keys have to do rather than the fingers: the keys are what carries the melody, making use of whatever finger or hand happens to be in the vicinity.
While the thought is soothing that this may have been written for two instruments or two manuals or different octaves, the progression of difficulty may point to this being written for the explicit purpose of exercising this kind of mental contortion.
Answer: This question is too problematic to completely answer.  The answer would depend on the instrument it is meant for and you need to specify that.  Since both staves are treble I am going to "assume" it's guitar music.
Based on the assumption...
You are not supposed to play both as this looks like duet music.
Having said that, if you want to rearrange it for solo guitar that may be possible (I didn't go that deep) but you may need to make some sacrifices with respect to the chord notes if they are not easy to play.
Comment: This is not guitar music Solo guitar music is written on one staff (treble.) One voice would have stems going up and a second voice would have stems going down. If it was for two guitars, the two staves would be surrounded by  a bracket, not a brace.
Comment: @HeatherS., I have an extensive collection of classical guitar music including duets.  They are printed exactly as the example in the OP (surrounded by a brace).  I do not believe that the various prints are all wrong.  The OP was confusing and ambiguous.  Also, it is not uncommon for guitar music to have doubled notes (a fingered note and an open string unison companion) hence even the title "...both hands are to play the same notes?" is unclear.
Comment: yes I get that guitar music can play the same note doubled, as guitar like all strings (and unlike piano) has options to play the same pitch in different places. I find it odd that the music would be braced instead of bracketed, but I guess I learn something every day.  My son and daughter are both classical guitarists.  I have never seen a solo piece written on two lines.  The OP's music selection does not make sense on piano.
Comment: I didn't say solo.  My answer mentioned duets.  Duets are bracketed as piano music.  Solo never, to voices as you say with stems in different directions.
Answer: If it's a piano piece, then the answer is simple.  You release the left hand notes once they have been played in order to make the (mainly) 'f' notes available in the right hand.  Use the pedal to make the left hand notes sound more sustained.
Comment: If it's a piano piece, then the fourth bar is horrendous. Both clefs have D's and F's that I'm (supposedly) expected to hold down and re-strike. Uggghhhhh, I can't believe I'm reading this sheet music (unless at least one clef is not for piano).
Comment: The forth bar is fine.  Since you are already playing the Ds in the right hand, you needn't play them in the left.  Pedalling will give the impression of the left hand dotted crotchet length Ds.


Is AudioServicesPlaySystemSound allowed to use in App Store apps?

Question: The AudioServicesPlaySystemSound function comes under System Sound Services. Is this service of AudioToolbox allowed to use?
AudioServicesPlaySystemSound(1012);

Or can it be rejected by Apple when submitting an app using it to the App Store?
Answer: Yes, it is allowed to use. It's actually documented in Apple Developer Documentation.
There are some limitations on what you can play with this method though:

Sound files that you play using this function must be:

No longer than 30 seconds in duration
In linear PCM or IMA4 (IMA/ADPCM) format
Packaged in a .caf, .aif, or .wav file

If you want level/timing control and the ability of playing multiple sounds at a time, use AVAudioPlayer instead, it's the generally recommended method.
Comment: I just want to play default push notification sound, which seems is allowed. Thanks!


Which workouts will most help my ball handling skills?

Question: I'm looking for some type of training exercise or workout that will help my ball handling ability.
I know that it is not a good idea to try to increase muscle mass, but instead try to work on your "twitch muscles".
With that being said, it seems like the most traditional workouts that you can buy or find at the gym are more geared toward creating muscle definition, building muscle mass, or losing weight. I'm not interested in that, I'm just interested in workouts that will most help my ball handling while playing basketball.
By "ball handling" I'm referring to:

dribbling, passing, or receiving the ball
Answer: When I played basketball in high school, I found that what helped my ball handling skills the most was that feel you get from constant repetition and muscle memory. Knowing exactly how hard and at what angle to put the ball behind your back, between your legs, how much wrist to use while dribbling, etc. - they're all critical skills that help your ball handling.
As most coaches will also tell you - being able to dribble the ball well with either hand is also important - as is being able to dribble with your head up, looking around the court.
Here are some drills I used to do at practice to improve my ball handling skills:

between the legs with each step from the baseline to the free-throw line, across the free throw line, and back to the baseline (so you make a rectangular path while doing this)
Dribble 2 balls at a time from one sideline of the court to the other, then back again. Start slow and don't go any faster than you can go without losing control of one (or both) balls.
Stand with your knees slightly bent and dribble the ball back and forth between each hand - from one side of your body to the other - behind your back. This helps with that feel I mentioned earlier.
Controlling your balance and center of gravity is also a key component of good ball handling skills. As your do these drills, pay attention to your balance and keep your center of gravity low to the ground, knees bent.
Answer: The best way to improve ball handling is to actually practice dribbling. You'll improve your passing and catching of the ball too because you'll improve your reaction time and get a better feel for the ball and how it comes off the ground at different angles, spins, and velocities. Few people go to the gym to practice their dribbling because it seems tedious. But if you can practice simple dribbling exercises, you give yourself time to really understand the nuances in controlling the ball.
Here are a few exercises that I used over the past few years. They increase in order of difficulty and should be completed in that order. These exercises might seem quite boring at first but if you practice them before more advanced drills, you'll have a much more solid control of the ball and consequently improve your crossovers, first step dribble, hesitation dribbles, etc...

Dribble the ball high up to your chin and slowly lower the apex of the ball down to your knees. In game scenarios, you need to be able to control your dribble at different heights.
Practice the above drill but dribble twice as hard. When you're trying to beat your defender to the basket, your dribble will be dramatically faster and more difficult to control. Dribbling hard will emulate this and improve your reaction time.
Practice the above drill but look at the hoop the entire time. It's obviously important to be able to keep your eyes up when dribbling. Once you become adept at this, you should always practice dribbling without looking at the ground and ball.
Practice the above with forward movement, and gradually increase your speed.

Keep these difficulty levels in mind and try implementing them into different styles of dribbling exercises.

crossovers in front of you left to right to left
between the legs alternating left and right foot forward
between the legs keeping the left and right foot parallel
behind your back left to right and back

It's important to be flexible in going from one type of dribble to another so try mixing them up: 1111222233334444, 12341234, etc...
Lastly, remember to vary the height of the ball, trying to keep the ball in your hands for various times (cupping the ball without carrying). Increase the intensity and speed of your dribble and once you have the dribble somewhat mastered, look up, bring in movement, and do the exercises until you feel completely comfortable.


How to connect url with port number in java with Jsoup?

Question: I am trying to get HTML in URL(.
Document doc = Jsoup.connect("URL").userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36").timeout(111110).followRedirects(true).execute().parse();
System.out.println(doc.text());

I did userAgent by Java(Jsoup): How to parse http://host:port But It does not work.
How should I connect that URL?
Comment: When you are writing: "But It doesn't work" what do you mean? Did you get an error? If yes what error?
Answer: You get the error because this URL under Cloudflare DDoS protection. If you open this URL in a browser you will see that first you got the 503 response code and after that, you will be redirected to the target URL. If you want you can set ignoreHttpErrors to true and you will see that with your code.
~ ➭ http http://www.kg348.com:8880/play
HTTP/1.1 503 Service Temporarily Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sat, 15 Jul 2017 14:58:52 GMT
Refresh: 8;URL=/cdn-cgi/l/chk_jschl?pass=sdfsdfsdf.127-dsfsdfd
Server: cloudflare-nginx
Set-Cookie: __cfduid=xxxx; expires=Sun, 15-Jul-18 14:58:52 GMT; path=/; domain=.kg348.com; HttpOnly
Transfer-Encoding: chunked
X-Frame-Options: SAMEORIGIN

And looks like this redirect has been done by javascript, but Jsoup is a parser, it doesn't include a javascript execution engine, so I'm not sure that you are able to get html code of target URL only with Jsoup. In order to execute javascript you will have to use something like selenium webdriver or alternative framework.
Comment: Thank you. I used wget with cookie option. Then parsed html with Jsoup.
Answer: JSoup allows you to connect to URL and parse the data based on the HTML/Javascript content of the website. Based on your code: Document returns an html document. Before trying the below code make sure you are able to connect to the website (Note i was able to view the website). So modify you code as below:
String url="http://www.kg348.com:8880/play"; // your webpage
Document parseURL = Jsoup.connect(url).get(); //will connect and fetch you the HTML content in URL

Next parse the elements in the Document using Elements class:
Elements ele=parseURL.select("<the html div you want to extract>");
for (Element element : ele) { //using foreach to iterate over every element inside your div or select method
            System.out.println(element.text());
}

Hope this will help :)

Edited:
Removed the timeout() from the Document.
Comment: Thank u! But "Document parseURL = Jsoup.connect(url).timeout(111110).get()" this does not work
Comment: Are you sure the website you are trying to parse has allowed your app to access? You may also try to leave the timeout portion of the code?


How can I develop this using induction?

Question: I'm trying to prove using induction that $a^n +b^n = (a-b) \cdot \sum\limits_{k=1}^{n}a^{n-k}b^k-1$
So I have developed the expression for $n+1$ but I get to $a \cdot b^n - b^{n+1} + a^n - b^n$
And from here I can't simplify until $a^{n+1} + b^{n+1} \ldots$
Can someone help me?
Thanks
Comment: You want $a^n-b^n$ on the left, not $a^n+b^n$.
Comment: And the $-1$ at the end of the formula should be part of the exponent of $b$.
Comment: Are you sure this is true.  a=b => 2a^n = 0 (or -1)
Answer: Induction step (assuming a and b are non-zero, of course);
$  (a-b) \cdot \sum\limits_{k=1}^{n+1}a^{n+1-k}b^{k-1} =$
$  \sum\limits_{k=1}^{n+1}a^{n+2-k}b^{k-1} - \sum\limits_{k=1}^{n+1}a^{n+1-k}b^k=$
$ a^{2}\sum\limits_{k=1}^{n+1}a^{n-k}b^{k-1} - ab \sum\limits_{k=1}^{n+1}a^{n-k}b^{k-1}=$
$ (a^2 - ab)\sum\limits_{k=1}^{n+1}a^{n-k}b^{k-1}=$
$ a(a - b)\sum\limits_{k=1}^{n}a^{n-k}b^{k-1} + (a^2 - ab)a^{-1}b^n=$
$ a(a^n - b^n) + (ab^n - b^{n+1})=$
$ a^{n+1} - ab^n + ab^n - b^{n+1}=$
$a^{n+1} - b^{n+1}$

How can I develop this using induction?


Create form for image selection from the content

Question: I have a content type with title and image field in it. Now, I want to show a form to the user which will show the image thumbnail, title and a checkbox below each image with the value of respective nid. So that user can select the image they like and submit it. Which will eventually take the nid and do some actions depending on the selected nid.
My question is how I will create such form from that content.
Answer: Like most things in Drupal there are a couple of different ways you could do this. A quick look into the challenge, reveals the Webform View module. Basically, it allows you to pull in a viw (list of your nodes) as selectable items, for a webform. Webforms are good if all you want to do is store (and email of course) the submitted values of a form for manually processing later. Webforms are typically used for feedback, survey, contact forms.
If you need to do something a little more flexible with the submitted values, alternatively you could use the Views Bulk Operations (VBO) module (add-on for Views) which provides this kind of functionality plus a lot more if you need it for other purposes too.
Basically, you would create a view listing your content items with the fields you want to display, and then add a "Bulk operations: Content" field, and select the "Pass ids as arguments to a page", and then specify the path you want the arguments sent to. The path could then be defined in your custom drupal module, and you could use the $arguments = func_get_args(); to get all the arguments sent through. e.g. in a sandbox_test.module
function sandbox_test_menu() {
  $items = array();

  $items['test-submit'] = array(
    'title' => 'VBO Test Submission handler',
    'page callback' => 'sandbox_test_vbo_test',
    'access callback' => TRUE,
  );

  return $items;
}

function sandbox_test_vbo_test() {
  $output = '';

  $args = func_get_args();
  if (is_string($args[0])) {
    $items = explode(",", $args[0]);
    $output .= '
' . print_r($items, true) . '
';
  }
  else {
    $output .= 'None found';
  }

  return $output;
}

Comment: Ah! one reply at last :) I was looking to this page every minutes to see if any answer is posted. And now, even the first reply looks very promising. I will give it a try. If it work, I will make it as accepted answer. Thanks for your reply anyway.


What approach should I take to learn Jazz/blues guitar?

Question: I played a bit of piano when I was younger, and a little guitar, but I lost most of it. I can still read sheet music, and taught myself the pentatonic scale, and I'm working on learning to recognize every note on the fretboard (please advise if that is necessary).My end goal is to learn to play jazz and blues. I feel as if I'm going through mostly basics, but what should I be able to do before I start learning anything blues or jazz related?
Comment: @Glenak1911 Hi - this question received a vote to close (not from me), because it's a bit too broad. I can see their point : could you be a bit more specific about what you're asking ? Eg what is it that makes you feel yoiu can't go ahead with learning blues/jazz right away ?
Comment: Get a teacher, or failing that, a book.
Comment: As far as the blues goes, it's very easy to get started. Learn the blues scale, learn the basic 12 bar blues pattern and just start playing.
Answer: While teachers and self-study are excellent ways to learn anything, when it comes to learning the blues, I believe you can profit greatly by finding someone who is just a little bit better than you, and just sit down and play together.
While the form has evolved over time to embrace real sophistication, it started as a type of folk music. Playing three chord gut bucket with a person long on enthusiasm and with just the right amount of technique can be a great way for you to start. The road might lead you to Gershwin and Fats Waller eventually - I hope it does - but starting with some one, two or three chord Muddy Waters tunes, learned in what my pals and I like to call a "chart-free zone," could introduce you to the freedom and ease that I believe is essential to satisfying performances of this rich, seminal style of music.
Keep in mind that some of the greatest practitioners of the art form began by playing on something called a diddley bow - a piece of wire stretched between two nails, (pinning a bottle against a barn door as a resonance chamber,) played with a broken bottle neck, rather like a mountain dulcimer, but nastier sounding. The aforementioned Mr. Waters, B.B. King and many others started this way.
You need not go that far back in time, but starting with a guitar, the right pal and a hankering to learn could get you a good start.
Enjoy, whichever method of learning you choose - understanding they are not mutually exclusive.
Comment: Good advice. Except for the underlying theory, improvisation is hard to learn from books. Listen to great players, and try to play with others as soon as possible.
Answer:
What should I be able to do before I start learning anything blues or
  jazz related?

You should be able to play the chords smoothly through the traditional I-IV-V blues progression in E,A,D,and G with a drum track. Then turn on your iPod and start playing along with simple blues music - Muddy Waters is a great blues artist to start with. His music is very listenable and enjoyable, well structured, generally well recorded (often a problem when listening to the old masters), played almost entirely in the above mentioned keys, and he covers pretty much all of the traditional blues forms and progressions at one point or another. Once you're mastered the above mentioned progressions, you'll be able to play along with him in no time, and you'll get a feel for playing the music and confidence to move forward.
Once you know those progressions well, the other thing is to get out there and play with others, in a context where you won't feel ashamed because you don't know that much, or you make a mistake. Play with recordings for a while until you feel you have enough chops and knowledge not to send people running out of the room, and you have enough confidence to mix in without worrying about making a total fool of yourself. Then just do it.
I think it's important to emphasize that the theory and approach behind jazz and blues is generally quite different than that of traditional classical or even "pop" music, except for the most basic aspects (and a lot of it can't even be expressed in terms of traditional theory) - so the sorts of study and practice regimens generally taught for such forms may be of limited use when dealing with jazz and blues: They are fundamentally improvisational and very flexible, personal forms of music. You will rarely hear a credible blues or jazz musician play the same piece the same way twice. This is true of all musical performances in varying degrees, but when it comes to blues and jazz it is much more noticeable and is arguably mandated by the genres themselves: They represent expressions of how the musician is feeling "in real time" - at the moment the music is being played. Charles Mingus writes (don't have a citation at the moment) about how the idea of a "jazz composer" is essentially an oxymoron. (He came up with a way to negotiate the problem.)
I'm not saying that you don't have to know theory or practice to play jazz and blues well - I'm just saying that it might be a different sort of theory and practice than what you are accustomed to.
Keep studying theory related to blues and jazz  - there is material out there - and practicing blues and jazz scales and chords and most importantly - LISTEN TO THE GREATS and PLAY WITH OTHERS. You'll get there.

I've found this book to be very helpful: The Jazz Language: A Theory Text for Jazz Composition and
  Improvisation
Answer: Listen a lot of jazz/blues songs you like. This will get the sound in your ears. Not Just guitar or piano, but more instruments (miles Davis, trumpet-charlie parker, sax- wes montgomery,guitar etc.)
Also get your theory right. A simple twelve bar blues Also has theory behind the three chords. Understanding This can be your first steps into a jazz blues.
It Also helps if you learn to play some recorded songs incl. Solos. This way you can steal nice chord voicings and licks. And as mentioned above, a great teacher saves you a lot (!!!) of time!


Can logistic regression output a non linear curve?

Question: I have a doubt regarding logistic regression.I know that it separates the data into 2 parts.Is it possible that it leads to a curve as shown in the example of underfitting and overfitting
What i know is that adding more layers(Neural networks) of logistic regression can cause these curves .My question is can a standalone Logistic Regression without any layer lead these types of non linear curves.
And if NO,how can we define the case of overfitting and underfitting in that scenario visually.
Comment: Logistic regression does not by itself separate cases into 2 classes. It models the log-odds of class membership. Any separation into predicted class membership depends on a choice of cutoff for predicted probabilities. That cutoff might have a default choice at p=0.5 (log-odds of 0) but that cutoff can be changed based on things like the relative costs of false-positives versus false-negatives.
Comment: Yes by 'feature engineering'. If you pass as input, x,y and eg  polynomial terms.
Comment: See https://stats.stackexchange.com/questions/127042/why-isnt-logistic-regression-called-logistic-classification/127044#127044
Answer: "Standalone" logistic regression can indeed only draw a straight line, as it defines a linear relationship between the predictors and the log of the odds (our response).
Overfitting can occur in logistic regression in exactly the same way that it can occur for regular linear regression. The reason it's hard to picture it using those diagrams is that you're only visualizing two dimensions, where the idea of over fitting isn't as intuitive.
So linear model overfitting is difficult to visualize precisely because it occurs when you are working in too many dimensions. So this might be side stepping your question, but I think it's actually best to not try and directly visualize it, but just think through an example step by step. Imagine that we're trying to predict someone's weight. We can create a simple linear model that is a decent fit using just their height, and that should generalize fairly well. If we add gender, that should will improve the fit, and also generalize well. But if we also add 26 binary variables based on whether or not they have a given first letter in their last name ("A", "B", "C", etc), well, in a small data set we might improve our fit (maybe the lone "Quinn" in our data set is very heavy, and we capture that), but it probably won't generalize very well (as we don't think there's any real association there). Hence, we are overfitting.
While that was using binary variables (starting letter, gender), it's the exact same concept, and still a linear model (but binary variables can be a little easier to visualize). The fact is, linear models over fit when they involve too many dimensions, relative to the actual sources of variability you're trying to capture in the observed data set. The concept of overfitting in logistic regression is the exact same, the only difference is your target (the log of the odds, not just any continuous response variable).
Comment: "Standalone" logistic regression is pretty obsolete.  Any continuous predictor can be expanded into a regression spline to allow for any degree of nonlinearity.
Comment: Of possible interest: https://datascience.stackexchange.com/a/79994/73930


How to organize objects in an array using various property values of that object with the ES6 sort method?

Question: I have an Array like this
let arr = [
    {label: "Bob Bobson", value: 17345, group: "Applicants"}
    {label: "Frank Frankson", value: 17347, group: "Applicants"}
    {label: "Bill Billson", value: 17348, group: "Applicants"}
    {label: "John Johnson", value: 1, group: "Caregivers"}
    {label: "Aaron Aaronson", value: 15, group: "Caregivers"}
    {label: "Jacob Jacobson", value: 172, group: "Clients"}
    {label: "Eric Ericsson", value: 1441, group: "Clients"}
    {label: "Doc Docson", value: 1147, group: "Doctors"}
]

I want to sort it using two of the property values in the object, the label property and the group property. I'm currently not getting any results however. I want to sort by group first and then label.
Here is what I am trying below.
arr.sort((a, b) => { a.label.toUpperCase() > b.label.toUpperCase()) ? 1 : -1 });

Using this I get the same results back, the label property doesn't get sorted.
Comment: FYI, `Array#sort` has existed for a long time. It's not new to ES6.
Answer: Your sort function isn't returning anything. Arrow functions can do an implicit return statement, but only if you have no curly brackets. So either remove the curly brackets, or add a return statement. Also, you have an extra closing parentheses after b.label.toUpperCase()
arr.sort((a, b) => a.label.toUpperCase() > b.label.toUpperCase() ? 1 : -1 );

arr.sort((a, b) => {
    return a.label.toUpperCase() > b.label.toUpperCase() ? 1 : -1
});

Comment: Ok i see this ends up sorting the label property and scrambles the group property.
Comment: Yes, i was showing you why no sorting was happening. If you want to modify the sorting condition further, feel free to.
Comment: to continue sorting it do I just chain the command ?
Comment: The function that you pass into .sort determines how it's sorted. If you want it to be sorted by group, then instead of comparing labels, compare groups. If you want it to be sorted by both, then compare both.
Comment: Ok got it , thanks. Yeah I wasn't returning a value which caused it to error up.


Triangle Construction By In-Center, Ex-Center and foot of an Altitude

Question: I am struggling to show that constructed triangle is indeed the desired one
Condition: In triangle $ABC$, one has marked the in-center, the foot of altitude from vertex $C$ and the center of the ex-circle tangent to side $AB$. After this, the triangle was erased. Restore it.
Analysis: Let $I$ be the in-center and $I_C$ be the ex-center and $H$ be the foot of altitude from $C$.
There are several ways of showing that $AB$ is the angle bisector of $\angle IHI_C$. This would restore the side $AB$. Lines $II_A$ and perpendicular to $H$ on $AB$ would intersect at point $C$.
Answer: Since outer and inner angle bisector are perpendicular we see that $A$ and $B$ are on circle with diameter $I_C I$. Then angle bisector of $IHI_C$ cuts this circle at $A$ and $B$. Now the perpendicular through $H$ on $AB$ cuts line $I_C I$ at $C$ and we are done.
Comment: Nice solution. Can you explain why $HI$ and $HI_C$ are symmetric with respect to $AB$?
Comment: I don't know yet, I used his hint.
Comment: I get this part but how can I be sure that I and I-C are indeed the in-center and ex-center respectively from this construction?
Answer: Just a little addendum to ChristianF's answer, explaining why $AB$ bisects $\widehat{IHI_C}$.
Let $J$ and $K$ be the projections of $I$ and $I_C$ on $AB$.

We have $AJ=BK=\frac{b+c-a}{2}$ and $AH=b\cos A=\frac{b^2+c^2-a^2}{2c}$, so $HJ=AJ-AH=\frac{(a-b)(a+b-c)}{2c}$.
Similarly $HK=AK-AH=\frac{(a-b)(a+b+c)}{2c}$. Since $r=IJ=\frac{2\Delta}{a+b+c}$ and $r_C=\frac{2\Delta}{a+b-c}$ we have
$$ \frac{r_c}{HK}=\frac{4c\Delta}{(a-b)(a+b-c)(a+b+c)}=\frac{r}{HJ}$$
hence $AB$ bisects $\widehat{IHI_C}$.
Comment: Great!..........


How to add remote repository in git with SSH?

Question: I just getting started using SSH keys due to managing multiple accounts in a single mac. It works very well when I tried to clone with SSH. However, when I tried to add a remote repository using SSH (git remote add origin firstname.lastname@example.com:jiwanjeon/26-django-practice.git) and push my files. It shows up this error message "firstname.lastname@example.com: Permission denied (publickey). fatal: Could not read from remote repository."
I googled so many times but I am not sure how to deal with it...

What I tried to
: I made a new SSH Key and add it in its' repository Deploy Key but it didn't work as well.

edit 1)
: I also tried to make a new SSH Keys and copy and paste it, also didn't work
edit 2)
When I tried to git add repository through HTTP not a SSH. It works as well but I am not sure why SSH didn't work even I add a SSH Keys...
I would appreciate your help!
Comment: https://stackoverflow.com/search?q=%5Bgit%5D+%5Bssh%5D+deploy+key+push
Comment: Deployment keys are read only. You can clone but cannot push with them. You need to remove deployment keys and add your key to your profile.
Answer: To use a remote repository, you must only make sure that you have SSH access to your server. Once there, you can follow these steps to create your remote repository in the link below.
https://www.inmotionhosting.com/support/website/git/setting-up-your-remote-repository-with-git/


Roaming Profiles, Folder redirection or... both

Question: I'm developing a remote desktop services in Windows Server 2008 R2. It's going on one server but in the future it's possible that another server could be added to the farm.
I'm creating roaming profiles and folder redirection to save space. I have some doubts... if I'm redirecting all the folders I can do that through GPO (start menu, desktop, appdata, My Documents, Videos, Music...), does it make sense to use roaming profiles?
I mean, I'm redirecting almost everything. So, if I don't use roaming profiles, what kind of data is not shared/roamed?
Perhaps it is not necessary and if I set roaming profiles, I will add more unnecessary complexity to the infrastructure.
Do you have and advice or recommendations?
Answer: The profile of a user contains the personalizations that the user configures in their user interface as well as the HKCU registry hive. If you don't use roaming profiles and have multiple servers users are logging into, a new profile will be created that will not contain any of the previously configured settings from any of the other servers.
IMO, roaming profiles along with redirected data folders are a good strategy for keeping all user data apart from servers that the users interact with. That way, if you ever lose a server or pull one from the farm for any reason, its pretty much plug a new one in and go forward.
Answer: Using a combination of both is the strategy that Microsoft recommends.
You should redirect as much as you can, as this reduces the amount of data that is copied during the logon/logoff process to the roaming profile folder.  All it takes is for a user to copy a 200 MB PowerPoint file to their desktop to blow a hole in your roaming profile strategy.
I would not redirect Application Data though.  This folder typically incurs a lot of activity during normal operation, and redirecting it can cause performance issues.
Comment: PSTs are a database file and as such does not play well with replication. Microsoft's answer is to use an exchange server.
Comment: Thanks for the answer.
Redir appdata could be a problem, but i think if you don't redirect that folder, you can have problems for example with Outlook PSTs, don't you think?
Comment: What is your opinion about PST files? If you don't redir the folder appdata, the size of appdata can grow a lot because of PST user files.
Regards and thank you.
Comment: There aren't any good answers for pst's.  Microsoft does not support or recommend them on network drives.


Semaphore e Mutex em C

Question: Eu tenho o seguinte problema:
Uma lan house com 3 pcs, vou inserir um valor X no terminal que será o número de clientes que chegam na lan house, os clientes só podem usar os pcs que estiverem desocupados, caso esteja ocupado vão para uma sala de espera, esta sala de espera suporta 15 clientes. Caso não tenha pc disponível nem espaço na sala de espera, o cliente simplesmente vai embora...
1) Sim, é um trabalho da faculdade;
2) Não, eu não quero nada resolvido de mão beijada;
3) Eu só preciso de uma ajuda para entender como resolver este problema....
Eu tenho lido bastante sobre semaphore, mutex, threads, mas mesmo assim o que precisa ser feito ainda é meio obscuro para mim.
Aqui é o pouquíssimo que escrevi tentando resolver este problema. Qualquer dica é muito bem vinda !
    #include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define ROOM_SIZE 15

sem_t queue, pc;
int room [ROOM_SIZE]; // 0 -> livre  |  != 0  -> ocupado
int pcsAvaliable = 3, roomAvaliable = ROOM_SIZE;
int computers[3] = {0, 0, 0}; // 0 -> livre  |  1 -> ocupado

struct Client{
    int id;
};

int check_computer()
{
    int i;
    for(i=0; i<3; i++)
    {
        if(computers[i] == 0)
            return i;
    }
    return -1;
}

void insert_waitingRoom(int idClient)
{
    int i;
    for(i=0; i< ROOM_SIZE; i++)
    {
        if(room[i] == 0)
            room[i] = idClient;
    }
}

void* Lan(void* arg)
{
    struct Client *cli = (struct Client*) arg;

    int idPC;
    int idClient = cli->id;
    if(pcsAvaliable > 0)
    {
        sem_wait(&pc);
        pcsAvaliable--;
        idPC = check_computer();
        if(idPC >= 0)
        {
            computers[idPC] = 1;
            printf("Cliente %d pegou pc %d\n", idClient, idPC);
            usleep( (   (rand() % 11) + 80) * 1000);

            computers[idPC] = 0;
            printf("Cliente %d deixou o pc %d\n", idClient, idPC);
            pcsAvaliable++;
        }
        sem_post(&pc);
        sem_post(&queue);

    }
    else
    {
        //Quando os pcs estão ocupados, o cliente fica na sala de espera.
        //Mas ele fica lá eternamente. Tem que fazer ele tentar entrar no PC e não o novo processo que vem da main.
        if(roomAvaliable >0)
        {
            sem_wait(&queue);
            roomAvaliable--;
            printf("Cliente %d foi posto na sala de espera !\n", idClient);
            insert_waitingRoom(idClient);
            while(pcsAvaliable <= 0)
            {
                //tentar acessar pc
            }

        }
    }

}

int main(int argc, char const *argv[])
{
    int i=0, j=1;

    if(argc > 1)
    {
        int numClients = atoi(argv[1]);
        sem_init(&pc, 0, 3);
        sem_init(&queue, 0, 15);
        pthread_t clients[numClients];

        //Create Clients
        for(i=0; i< numClients; i++)
        {
            struct Client* cli = (struct Client*) malloc(sizeof(*cli));
            cli->id = i;

            pthread_create(&clients[i], NULL, Lan, (void*)cli);
            usleep( (   (rand() % 5) + 1) * 10000);
        }
    }
    else
        printf("Por favor. Informe o número de clientes");

    sem_destroy(&pc);
    pthread_exit(NULL);
    return 0;
}

Answer: Primeiramente minha sugestão é criar uma estrutura de 3 espaços para os PCs (ou um char de 3 espaços).
typedef struct{
    char *nome;
    char status : 2; // 0 - livre | 1 - ocupado
    // O ": 2" especifica que em status, o valore máximo será
    // 1 e o mínimo será 0 (os valores atribuídos recebem % 2)
}PC;

Com essa estrutura será possível saber qual PC estará desocupado quando escrever o nome.
O método Lan tem um parâmetro, e nada mais correto que usá-lo. Nesse método, a única coisa que acontecerá será marcar o PC como desocupado e/não escrever o nome do PC.
A quantidade de Threads necessárias para o sistema é a quantidade de PCs que a lan-house possui.
Os clientes que extrapolarem ROOM_SIZE+3 não precisam ser inclusos no laço, pois eles irão embora de qualquer jeito.
O main controlará a quantidade de pessoas que ainda estão em esperá e verificará quais PCs estão estão disponíveis, assim sempre que um PC estiver livre, já iniciará uma nova Thread para esse PC.
O código funciona normal sem o pthread_join, mas não há problema em usá-lo, se for usar, deixe ele logo abaixo do pthread_create.
Comment: Obrigado pela ajuda. Meu maior problema é em usar os semáforos, não consigo fazer os clientes usarem os 3 Pcs e ficarem na fila de espera. Eles ficam revezando entre 0,1,2, 2, 2, 2, 2, 2,2 (fica eternamente entrando e saindo do 2). :O
Comment: @PlayHardGoPro, se precisar e/ou estiver interessado, posso colocar na explicação o trecho em que é feito o semáforo para controlar os PCs livres
Comment: Hey. Atualizei meu código, aparentemente (eu acho) que estou conseguindo controlar os clientes nos 3 pcs e estão revezando todos os pcs (não somente o 2 como estava antes). MAS, eu até "insiro" o  cliente na fala, porém não consigo fazer ele disputar o computador novamente. O Novo cliente (vindo do main), assume o pc e o fulano fica na fila eternamente. Poderia dar uma olhada ?

Semaphore e Mutex em C


If $x$ is any positive real number, then prove that there exists a non-negative integer denoted by $[x]$ such that $[x]\leq x<[x]+1$

Question:
If $x$ is any positive real number, then prove that there exists a non-negative integer denoted by $[x]$ such that $[x]\leq x<[x]+1$.
(A Hints is given as: Apply Archimedean Property in $\mathbb{R}$)

I know the Archimedian property as:
If $a(>0), b\in \mathbb{R}$, then there exits at least one positive integer $n$, such that $na>b$.
here, how to choose $a,b, n$.? How to use the theory to prove the result.
Comment: Your "Archimidean property" is actually a corollary of the Archimidean property that for every real number $x$ there exists a natural number $n$ such that $n>x$
Comment: Don't you think this is the definition for the greatest integer function?
Comment: @StubbornAtom Yes. the definition is for the greatest integer function. But how to prove by Archimedean Property is a problem
Comment: @smcc Yes. I understand.  Applying Archimedean Property how to prove that.
Comment: This appears to be http://math.stackexchange.com/questions/117734/proof-of-greatest-integer-theorem-floor-function-is-well-defined restricted to positive reals.
Answer: AP $\implies$ there exist $n$ such that $n > x$. The set X = {$m: m>x$} is a non empty set of positive integers so it has a minimum element $k$. Then $[x] :=k-1$ (if $k -1 > x$ then $k-1$ is an element of $X$ but it can't be so $k-1 \le x$)
Comment: If $x$ is not an integer, would't it be $[x] = k-1$? We're supposed to have $[x]\leq x$, after all.
Comment: @Arthur right! see edit


Let $f(x)=4x^3-3x^2-2x+1,$ use Rolle's theorem to prove that there exist $c,0<c<1$ such that $f(c)=0$

Question: Let $f(x)=4x^3-3x^2-2x+1,$ use Rolle's theorem to prove that there exist $c,0<c<1$ such that $f(c)=0$

$f(x)=4x^3-3x^2-2x+1,$ is continuous and differentiable but the third condition of
Rolle's theorem is not met,so Rolle's theorem is not applicable here.
I am stuck here.
Comment: $f(c)=0$ or $f'(c)=0$
Answer: Let $g(x)=x^4-x^3-x^2+x$. Then $g'(x)=f(x)$.
$g(0)=g(1)=0$.
By Rolle's Theorem, there exist $c$ such that $0<c<1$ and $g'(c)=0$.


List 3rd party WMI providers before rebuilding repository

Question: I'm looking for some Powershell cmdlet/script which list WMI 3rd party providers before I will rebuild whole repository.
There is GWMI cmdlet which lists all WMI objects but I'm missing something like "Company:", then I would use filter to list non-microsoft WMIs.
<code>Get-WmiObject -List | fl *
...
PSComputerName   : MyComputer
Name             : __SystemClass
__GENUS          : 1
__CLASS          : __SystemClass
__SUPERCLASS     :
__DYNASTY        : __SystemClass
__RELPATH        : __SystemClass
__PROPERTY_COUNT : 0
__DERIVATION     : {}
__SERVER         : MyComputer
__NAMESPACE      : ROOT\CIMV2
__PATH           : \\MyComputer\ROOT\CIMV2:__SystemClass
Path             : \\MyComputer\ROOT\CIMV2:__SystemClass
Derivation       : {}
Methods          : {}
Scope            : System.Management.ManagementScope
Options          : System.Management.ObjectGetOptions
ClassPath        : \\MyComputer\ROOT\CIMV2:__SystemClass
Properties       : {}
SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers       : {abstract}
Site             :
Container        :
....
</code>
Is there any way how to detect 3rd party WMI providers?
Thank you for any help.
Answer: Given how WMI was built and implemented you're a bit SOL on a magical solution.  I can help you some of the way, but you're still going to have to eyeball the results.  Essentially you need to start with a list of providers which you can get with the following code:
<code>$Providers = Get-WmiObject "__win32provider"
</code>
If the array count is short eyeball the provider names.  Microsoft didn't use a standard naming convention so you can forget filtering with something useful like "MSProvider".
3rd parties were advised and asked, yet not required, to create their providers for their own namespaces.  Anything not in "CIMV2" should stand out and be looked at more closely.  For reference you can review how 3rd parties register a WMI provider and what information is required when doing so here.
The objects returned by the code above have a CLSID property which corresponds to their entry in the Windows registry.  You could loop through them and query the registry and see if a 3rd party added any values to the key you could use to identify them with.
Happy hunting.


How to show only non-bold text of toast

Question: In Windows 10 and with Visual Studio 2017 I try to send a toast of UWP app which shows only regular text not bold one. According to the MSDN ToastTemplateType.ToastText01 should show regular text but doesn't.
How can I make all regular text toast message?
private void Button_Click(object sender, RoutedEventArgs e)
{
    ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;

    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);

    XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");

    toastTextElements[0].AppendChild(toastXml.CreateTextNode("content content content content content content content content content content "));

    ToastNotification toast = new ToastNotification(toastXml);

    ToastNotificationManager.CreateToastNotifier().Show(toast);
}

Answer: if you're writing a UWP app, you should be using the UWP ToastGeneric toast templates.
However, regardless of that, you can not have a toast that only has non-bold text. The first text element (the title) will always be displayed as bold in builds 16299 and higher of Windows 10. That is simply the new visual style of toasts.

How to show only non-bold text of toast


Azure DevOps with self-hosted Ubuntu machine: docker fails

Question: I created an Azure DevOps agents based on the Ubuntu image that can be found here: https://github.com/Microsoft/azure-pipelines-image-generation
After I deployed the machine and installed the agent (see https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/v2-linux?view=vsts) I ran a Docker task and got the following error:

dial unix /var/run/docker.sock: connect: permission denied

What do I have to do to get the Docker task executed successfully?
Answer: The problem is that the agent service has not the permissions to connect. You can either run the agent service as root (sudo ./svc.sh install root) what I would not recommend or add the user to the Docker group via sudo usermod -a -G docker $USER.
Then logout and and log in again and it should work.
See also https://docs.docker.com/install/linux/linux-postinstall/
Comment: (But remember that anyone who can run any `docker` command can trivially get root on the system; guarding it behind `sudo` is not wrong.)


Buzzing sound on first two fret when playing G string on Electric Guitar

Question: I started playing electric guitar for about 1 week now so I'm pretty new to this stuff
The problem here is when I play G string on first or second fret there is buzzing sound
The rest of frets or string are fine
The open G sounds OK unless you hit it relatively hard and you here the buzzing sound again.
So what can I do for this?
Answer: Raise the saddle that's under the 3rd string. There will be two little grub screws that need turning, until the buzz goes.
Answer: I'd say there isn't enough info to diagnose.  There may be issues with a fret coming up.  If there is an uneven bump in the frets this may cause buzzing for just one or two notes on one string.  Does the 1st and 2nd fret buzz for the other strings too?
Is your guitar new of older, used?  If new then it may need an adjustment, bridge and truss rod (which I don't recommend doing on your own w/o experience).  If it's old look for indentations on the frets.  If there are some then you have uneven wear on the frets and that requires the frets to be filed down, possibly replaced.
Answer: Do you only notice this when playing without an amp? I was once advised by a luthier at a local guitar shop that electric guitars are designed to be played through amplifiers. As such, it's not "fair" to judge slight string buzzing when played without amplification. Do you notice the buzz when playing with moderate amplification?