text:
Q: How MQ Client like Java Client listen messages from MQ Server running ServerConn Channel I am looking for detailed description on how IBM MQ Client or listener get the messages from MQ Server when new messages are placed on MQ Queue or Topic.

*

*How the connection between MQ Client and MQ Server are created?

*Does MQ Client initiates the connection with Server or does server initiates the connection to its consumer?

*In case we have connection pool defined on MQ Client, how client knows that it has to create more connections with Server as the messages are increasing on Server? How Client know about the messages on Server?

*Is there a communication from Server to Client which tells client that new messages have arrived?

I am looking for these details not the details on how this is setup or how to setup MQ Channels or Listeners. I am looking for how it works behind the scene.
If someone can point me to the right direction or documentation, it would be great.

A: It's hard to speak definitively about how the IBM WebSphereMQ client & server work since they're closed source, but based on my experience with other messaging implementations I can provide a general explanation.
A JMS connection is initiated by a client to a server. A JMS client uses a javax.jms.ConnectionFactory to create a javax.jms.Connection which is the connection between the client and server.
Typically when a client uses a pool the pool is either filled "eagerly" (which means a certain number of connections are created when the pool is initialized to fill it to a certain level) or "lazily" (which means the pool is filled with connections one-by-one as clients request them from the pool). If a client requests a connection from the pool and if all the connections in the pool are being used and the maximum size of connections allowed by the pool hasn't been reached then another connection will be created. If the pool has reached its maximum allowed size (i.e no more connections can be created) then the client requesting a connection will have to wait for another client to return their connection to the pool at which point the pool will then give it to the waiting client.
A JMS client can find out about messages on the server in a few different ways.
If the JMS client wants to ask the server occasionally about the messages it has on a particular queue it can create a javax.jms.Consumer and use the receive() method. This method can wait forever for a message to arrive on the queue or it can take a timeout parameter so that if a message doesn't arrive in the specified timeout the call to receive() will return.
If the JMS client wants to receive a message from a particular queue as soon as the message arrives on the queue then it can create a javax.jms.MessageListener implementation and register it on the queue. When such a listener is registered on a queue then when a message arrives on the queue the server will send the message to the listener. This is sometimes referred to as a "callback" since the server is "calling back" to the client.

A: The first thing you should do is take a course on JMS/IBM MQ or go to the new IBM conference called: Integration Technical Conference
Ok, now to your questions:

*

*How the connection between MQ Client and MQ Server are created?

You simply issue the createQueueConnection method of QueueConnectionFactory class and specify the credentials.
QueueConnection conn = cf.createQueueConnection("myUserId", "myPwd");

*Does MQ Client initiates the connection with Server or does server initiates the connection to its consumer?

MQ client application starts the connection - always.

*In case we have connection pool defined on MQ Client, how client knows that it has to create more connections with Server as the messages are increasing on Server? How Client know about the messages on Server?

It is up to the team's architect or lead developer to understand message flow and message patterns.  Hence, they will know what to set the pool count at.  Also, lots and lots of testing too.  Some client applications will only require a pool count of 10 whereas other applications may need a pool count of 50 because it is a heavy flow.

*Is there a communication from Server to Client which tells client that new messages have arrived?

You use the createReceiver method of the QueueSession class to retrieve a message.  Set a timeout value for the createReceiver method rather than continuously polling the queue manager.
Again, some training on the use of JMS/IBM MQ is strongly recommended.


text:
Q: Search inside hash in another class I have the following structure:
policies/permissions
Inside permissions folder:
car.rb
bus.rb
bike.rb

Every permission file has a hash:
MAPPING = {
   create: [:admin]
   delete: [:admin]
   etc
}

On Permission class (policies folder) I have the following method to check permissions:
class Permission
   def self.keys_for(model)
     # ?
   end
end

How can I dynamically search the MAPPING hash based on the model that is being passed as parameter ?
Thanks.

A: class Permission
  def self.keys_for(model_name)
    eval(model_name).const_get(:MAPPING)
  end
end

But, have you considered an implementation in which Permission is a concern that gets included into each model so that you don't have to pass the classes around explicitly?

A: class Permission
  def self.keys_for(model)
    f = File.open("#{model}.rb") #f give you the permissions hash
  end
end

notes : make sure that model param is the same as file name and also take care for path of files.
Hope you got my point

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stop ReadDirectoryChangesW from other thread I use next code to know when a files is changed in a certain folder:
HANDLE hDir = ::CreateFile(path, FILE_LIST_DIRECTORY, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED, NULL);

FILE_NOTIFY_INFORMATION returnData[1024];
DWORD returnDataSize = 0;

while(ReadDirectoryChangesW(hDir, returnData, sizeof(returnData), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|FILE_NOTIFY_CHANGE_LAST_WRITE, &returnDataSize, NULL, NULL))
{
    ...
}

ReadDirectoryChangesW blocks the thread until a file changes occurs. Is there any way to stop/force return from this function?

A: From your description, it sounds like CancelIoEx should do the trick. Obviously, you need another thread for that, since you're now calling it synchronously. That blocks the calling thread, so you can't do anyting from that thread, not even stop.

A: I think you need to take a look at this blog post: http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html
It's a lengthy post, but it's very informative and it talks about all the issues associated with this method.

A: You need to call this API function in its asynchronous mode of operation. You achieve this, as with many other file APIs, by passing an OVERLAPPED struct to the API call.
When you operate asynchronously the function will return immediately and it's up to you when you choose to collect the results. You can test whether or not the function is ready to supply results, you can opt to be notified that the API has results available, you can cancel the pending I/O, and you can choose to block until results are available. There is an awful lot of flexibility and naturally the API is more complex to use in asynchronous mode.
There is lots of information on MSDN about overlapped I/O. Start here: Synchronization and Overlapped Input and Output.

A: If you want the blocking call to return from another thread, change something that will make the call return - create a temporary file, perhaps.


text:
Q: Praise all alike Praising all alike is praising none.
This sentence is fine.
But if I say
Praising alike all is praising none.
This is a bit weird. Why?
Is there any rule that governs placing adverbs in a sentence?

A: In general, modifiers should be placed closest to the object that they are modifying.
The first sentence is correct because the placement of "alike" to modify "to praise" has to come after the collective noun "all" because "praise all" is a verb phrase.  So, while the adverb is not right next to the verb it is modifying, it's as close as possible.
To see why the second example is awkward and incorrect, we can use a more familiar1 phrasing:

We praised him highly.

is correct, in contrast with

We praised highly him.

1 I only say this because this sentence is more of an aphorism than something you would write in a day-to-day context.


text:
Q: Javascript text alert How can I use JavaScript to recognize  if a text box is filled, and if not, to alert me that it must be filled.
I have tried using
function myFunction() {
    alert

A: You can try with the following fiddle, but its better if you google your query because it is just a basic query:
$("button").click(function(){
  var inputVal = $("input[name=input]").val();
  if(inputVal == "" || inputVal == null){
    alert("Please fill the box");
  }else{
    alert("Good to go");
  }
});

https://jsfiddle.net/thisisdg/s7bovqvw/


text:
Q: calling a stack function in a tab navigator causes app to crash I have noticed that in my App.js, when I call my function MyTabs(which holds a stack navigator) in my tab navigator it causes the app to crash on IOS when run locally.
When the app does crash, I noticed zero errors are logged. I do not get errors in my terminal or on the screen. I am running it through npm start along with the expo app on my personal device. I have tried other devices as well but still the same crash. I also do not have a mac, I bet using xCode could atleast give me an error.
I have included a snack demo here as well as a git repository including every file in the project here.
Any insight at all would be greatly appreciated.
EDIT:: I am assuming since it works on snack it must be my environment. I have tried an entirely different computer and device but I have always started it using npm start and the expo app.
EDIT 2:: I noticed I do get this warning. Could something like this cause it to crash?
Here is the app.js
const Tab = createBottomTabNavigator();

function MyTabs() {
  return (

    <Stack.Navigator
     initialRouteName="Home">
        <Stack.Screen name="Home" component= {Home} options={{headerShown: false}}/>
    </Stack.Navigator>

);
}

export default function App() {

  return (
   <NavigationContainer>
    <Tab.Navigator
    initialRouteName="Home"
    screenOptions={{
      tabBarActiveTintColor: '#F60081',
      tabBarInactiveTintColor: '#4d4d4d',
      tabBarStyle: {
        backgroundColor: '#d1cfcf',
        borderTopColor: 'transparent',

      },

    }}
  >
    <Tab.Screen
      name="Home"
      component={MyTabs}
      options={{
        tabBarLabel: 'Home',
        headerShown: false,
        tabBarIcon: ({ color, size }) => (
          <MaterialCommunityIcons name="home" color={color} size={size} />
        ),
      }}
    />
  </Tab.Navigator>
</NavigationContainer>
);
}

const Stack = createStackNavigator();

A: Delete the package-lock.json and node_modules and run npm install again.

I was getting this error:

Cannot find module
'/stackoverflow/node_modules/vlq/dist/vlq.js'.
Please verify that the package.json has a valid "main" entry

After installing a package, I was getting same error for a different packages. Looks like packages could not communicate each other

A: Based on your Edit 2 try this
npm uninstall react-native-gesture-handler react-native-screens

then as the link says install the packages with expo install command again to be sure that you have the compatible versions in your expo project


text:
Q: Broken links after upgrading to 2.3.3 I've recently upgraded to 2.3.3 via Installatron on cpanel, now when I visit my home page I have links to other product pages within the navbar and links to the same pages from images that populate the home page.
The links from the navbar do not work but point to the same page as the image links which do work.
The address bar redirection addressees are exactly the same but the images link you get to view the particular product but using the nav links return a 'The page isn't redirecting properly' error.
I've run php bin/magento -> indexer:reindex -> cache:flush -> setup:upgrade
Any ideas?

A: Please run Following Commands after Upgrade:
composer update

Then
php bin/magento s:up && php bin/magento s:d:c && php bin/magento s:s:d -f

Then
php bin/magento indexer:reindex

Then
php bin/magento catalog:images:resize

Then
php bin/magento c:c && php bin/magento c:f && chmod -R 777 var/ pub/ generated/

Hope this will solve your problem!!

A: I had to upgrade our Magento store using only the command line and the broken links issue was solved.
I'm not sure why, but installing via Installatron on Cpanel was the cause of the broken links?


text:
Q: Azure Service Fabric Previous Installation after CleanFabric I'm trying to reinstall Azure Service Fabric after (probably incorrectly) running clean on one of the nodes in a cluster.
I've run CleanFabric.ps1 and got the following result:
FabricInstallerSvc is already removed.
FabricSetup.exe is no longer in FabricCodePath. Uninstall may have already run.

When I run TestConfiguration.ps1 for a one-machine node I get the following result:
    Microsoft.Azure.ServiceFabric.WindowsServer.5.3.301.9590> .\TestConfiguration.ps1 -Clust
    erConfigFilePath .\ClusterConfig.Unsecure.DevCluster.json
    Trace folder already exists. Traces will be written to existing trace folder: Microsoft.Azu
    re.ServiceFabric.WindowsServer.5.3.301.9590\DeploymentTraces

    Previous Fabric installation detected on machine localhost. Please clean the machine.
    Run Test-ServiceFabricConfiguration or TestConfiguration.ps1 to validate configuration & environment state. Best Practic
    es Analyzer hit validation error(s).

    LocalAdminPrivilege        : True
    IsJsonValid                : True
    IsCabValid                 : True
    RequiredPortsOpen          : True
    RemoteRegistryAvailable    : True
    FirewallAvailable          : True
    RpcCheckPassed             : True
    NoConflictingInstallations : True
    FabricInstallable          : False
    Passed                     : False

I've searched around trying to find a solution to this or some documentation on CleanFabric and have been unsuccessful. Anyone know how to completely clean the machine to reinstall Service Fabric on it?

A: In case others run into this issue on a local machine running windows here's what I did to fix it: Make sure the clean fabric was indeed run first. Then go to the key: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Service Fabric]
 and make sure paths that it references are manually deleted (if you run into process running files you're trying to delete just go into safe mode then kill it all) after you cleared all the directories out delete the key itself. This allowed me to reinstall a new cluster on the nodes.


text:
Q: Azure Machine Learning compute instance : Static IP address? I have a SQL Server database which is accessible only by whitelisting IP addresses. I would like to use an Azure Machine Learning compute instance to run some python code to query the database using the pyodbc library.
Does a compute instance in Azure Machine Learning have a static IP address ?
If yes, can I safely provide this address to be whitelisted or is there a risk that it might change through time ?
Thank you very much.


text:
Q: Mailgun emails are rejected everywhere but on Gmail My problem and Mailgun logs
I've "setup and verified" (see context) my sending domain with Mailgun, so I could use it to deliver my contact/order forms via Mailgun API: https://github.com/mailgun/mailgun-php
After successful verification (according to Mailgun) emails get delivered to Gmail addresses only though. Those are error logs provided by Mailgun for other email providers:
{
  "severity": "temporary",
  "tags": [],
  "storage": {
    "url": "https://so.api.mailgun.net/v3/domains/mail.itvar.cz/messages/***",
    "key": "***"
  },
  "delivery-status": {
    "tls": true,
    "mx-host": "mx1.seznam.cz",
    "attempt-no": 2,
    "description": null,
    "session-seconds": 2.4669690132141113,
    "retry-seconds": 900,
    "code": 451,
    "message": "451 4.4.8 Unroutable email address.",
    "certificate-verified": true
  },
  "recipient-domain": "seznam.cz",
  "event": "failed",
  "campaigns": [],
  "reason": "generic",
  "user-variables": {},
  "flags": {
    "is-routed": null,
    "is-authenticated": true,
    "is-system-test": false,
    "is-test-mode": false
  },
  "log-level": "warn",
  "timestamp": 1473673115.668517,
  "envelope": {
    "transport": "smtp",
    "sender": "postmaster@mail.itvar.cz",
    "sending-ip": "209.61.151.224",
    "targets": "***@seznam.cz"
  },
  "message": {
    "headers": {
      "to": "***@gmail.com",
      "message-id": "20160912092829.59867.45844.82A5D054@mail.itvar.cz",
      "from": "redakce@itvar.cz",
      "subject": "Tvar / Objednávka předplatného poštou"
    },
    "attachments": [],
    "recipients": [
      "***@gmail.com",
      "***@seznam.cz",
      "***@gmail.com"
    ],
    "size": 20723
  },
  "recipient": "***@seznam.cz",
  "id": "***"
}

TLDR: 451 4.4.8 Unroutable email address.
{
  "severity": "permanent",
  "tags": [],
  "storage": {
    "url": "https://so.api.mailgun.net/v3/domains/mail.itvar.cz/messages/***",
    "key": "***"
  },
  "delivery-status": {
    "tls": false,
    "mx-host": "postak.satoya.cz",
    "attempt-no": 1,
    "description": null,
    "session-seconds": 2.6076178550720215,
    "code": 505,
    "message": "505 Your domain has no DNS/MX entries",
    "certificate-verified": false
  },
  "recipient-domain": "itvar.cz",
  "event": "failed",
  "campaigns": [],
  "reason": "generic",
  "user-variables": {},
  "flags": {
    "is-routed": null,
    "is-authenticated": true,
    "is-system-test": false,
    "is-test-mode": false
  },
  "log-level": "error",
  "timestamp": 1473672066.691422,
  "envelope": {
    "transport": "smtp",
    "sender": "postmaster@mail.itvar.cz",
    "sending-ip": "209.61.151.224",
    "targets": "redakce@itvar.cz"
  },
  "message": {
    "headers": {
      "to": "***@gmail.com",
      "message-id": "20160912092103.8512.76522.0B575386@mail.itvar.cz",
      "from": "redakce@itvar.cz",
      "subject": "Tvar / Objednávka předplatného poštou"
    },
    "attachments": [],
    "recipients": [
      "***@gmail.com",
      "***@predplatne.cz",
      "***@itvar.cz",
      "***@gmail.com"
    ],
    "size": 20917
  },
  "recipient": "redakce@itvar.cz",
  "id": "***"
}

TLDR: 505 Your domain has no DNS/MX entries
{
  "severity": "permanent",
  "tags": [],
  "storage": {
    "url": "https://so.api.mailgun.net/v3/domains/mail.itvar.cz/messages/***",
    "key": "***"
  },
  "delivery-status": {
    "tls": true,
    "mx-host": "ax.virusfree.cz",
    "attempt-no": 1,
    "description": null,
    "session-seconds": 1.5925419330596924,
    "code": 553,
    "message": "553 sorry, your envelope sender domain must exist (#5.7.1)",
    "certificate-verified": true
  },
  "recipient-domain": "predplatne.cz",
  "event": "failed",
  "campaigns": [],
  "reason": "generic",
  "user-variables": {},
  "flags": {
    "is-routed": null,
    "is-authenticated": true,
    "is-system-test": false,
    "is-test-mode": false
  },
  "log-level": "error",
  "timestamp": 1473672065.693317,
  "envelope": {
    "transport": "smtp",
    "sender": "postmaster@mail.itvar.cz",
    "sending-ip": "209.61.151.224",
    "targets": "***@predplatne.cz"
  },
  "message": {
    "headers": {
      "to": "***@gmail.com",
      "message-id": "20160912092103.8512.76522.0B575386@mail.itvar.cz",
      "from": "redakce@itvar.cz",
      "subject": "Tvar / Objednávka předplatného poštou"
    },
    "attachments": [],
    "recipients": [
      "***@gmail.com",
      "***@predplatne.cz",
      "***@itvar.cz",
      "***@gmail.com"
    ],
    "size": 20933
  },
  "recipient": "***@predplatne.cz",
  "id": "ZKO8IRlbQgqDZ-nrxn0tKg"
}

TLDR: 553 sorry, your envelope sender domain must exist (#5.7.1)
Context
To complicate things further, the domain http://itvar.cz stays in hands of the previous webdesigner / hosting company. That is because the old web of my client is essentially nonmigratable (as I was told) and still needed to work on http://old.itvar.cz.
That means, that:

*

*www requests are transfered to my web with the new hosting and its friendly provider

*everything else stays with the old provider

*I can't personally configure anything, I can only send instructions.

I've sent the logs to the old provider and he essentially told me, that this is a problem of Mailgun. To my very limited knowledge of DNS configuration it does not appear so.
Questions

*

*Is this really problem on Mailgun or the old provider configured DNS badly and I should press him more.

*Can the problem lie with the sender "redakce@itvar.cz"? This email address exists, but it is, again, managed by the old provider, so I do not know much about it.

*Do you see anything else that can cause the problem?

*edited: The old provider noticed this field in the logs: Default SMTP Login > postmaster@mail.itvar.cz. This email address did not exist on the domain mail.itvar.cz. Could that be an issue? He created the address and so far, the issue is not fixed.
Apologies
If it's not clear already, I really know nothing about DNS configuration and domain setup. If that means, that I haven't provided neccessary information or (by the contrary) shared something sensitive, please let me know.
Those are some related questions I've found, but nothing seems to mention similar errors:

*

*smtp relay only works on gmail accounts

*Emails are not received on any email account except Gmail and Hotmail

*Emails are being rejected by some email providers
EDIT: Issue is resolved
My domain fixed something on his end, so my order forms are working now. I am still waiting for his reply what exactly it was, but for now, it seems pretty apparent, that the problem was with the domain DNS configuration.
Once I will know more, I will answer my question myself.


text:
Q: repeat control, have a dynamic column I have made a utility custom control to have a quick, generic view. the custom control has as properties a property names collection  which is of type object and received an arraylist of java objects (e.g. a Customer object).
Then  on the cc a repeat control is using this:
<xp:repeat id="rptObjects" var="obj" indexVar="idx" value="#{javascript:compositeData.collection}" >

I would like to make the columns more dynamic. So I defined a new property called linkName, also of type object.
The in my repeat control I have setup a div with a xp:link control:
<xp:link escape="true" text="#{javascript:compositeData.linkName}">

However I am struggling on the page that contains this cc to compute the value for the linkName property.
If for example I would like to use the name field on a Customer java object how should I compute the valeu for the linkName property?

A: on my cc I set the text for the link:
<xp:link escape="true">
                                    <xp:this.value><![CDATA[#{javascript:return compositeData.pageLink + "?unid=" + obj.unid}]]></xp:this.value>
                                    <xp:this.text><![CDATA[#{javascript:var lbl = compositeData.linkName;
obj[lbl]}]]></xp:this.text>
                                </xp:link>

on my xpage i could set:
<xc:ccUtilsGenericView pageLink="customer.xsp"
                    header="Customers" icon="fa fa-user" linkName="custName">


text:
Q: How to deploy a sybase proc from java class I have 10-12 procs which I need to deploy in Sybase server to work on my project.It's quite difficult and time consuming to repeat this process every time.I'm writing a java class which will make a connection and then read those files and just deploy it in the server.
But I'm getting SybSqlException.
Following is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class PlayProcsExecutor {

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    String DB_URL = "jdbc:sybase:Tds:abc.net:3700";
    String USER = "1234";
    String PASS = "abcd";
    BufferedReader br = null;
    StringBuffer stringBufer = new StringBuffer();
    try {
      //STEP 2: Register JDBC driver
      Class.forName("com.sybase.jdbc3.jdbc.SybDriver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();

      br = new BufferedReader(new FileReader("C:\\dummy_hi.sql"));
      String currentString = null;
      while ((currentString = br.readLine()) != null) {
        stringBufer.append(currentString);
        System.out.println(currentString);
      }
      String sql;
      sql = stringBufer.toString();
      System.out.println(sql);
      boolean rs = stmt.execute(sql);
      if (rs) {
        System.out.println("SUCCESS");
      } else {
        System.out.println("FAIL");
      }
      stmt.close();
      conn.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

Following is the proc :
use ams_trading

go

if object_id("#batch_mdl_list") is not null

    drop table #batch_mdl_list

go

create table #batch_mdl_list

(
    id_batch int not null,

    id_mdl int not null

)

if object_id("dummy_hi") != null

    drop proc dummy_hi

go

create proc dummy_hi

    @cd_stage varchar(12) = 'ALL',

    @debug int = 0

as

    select "HI"

go

if object_id("#batch_mdl_list") is not null

    drop table #batch_mdl_list

go

grant execute on dummy_hi to wm_role

go

The exception I'm getting is:
com.sybase.jdbc3.jdbc.SybSQLException: Incorrect syntax near 'object_id'.

    at com.sybase.jdbc3.tds.Tds.a(Unknown Source)
    at com.sybase.jdbc3.tds.Tds.nextResult(Unknown Source)
    at com.sybase.jdbc3.jdbc.ResultGetter.nextResult(Unknown Source)
    at com.sybase.jdbc3.jdbc.SybStatement.nextResult(Unknown Source)
    at com.sybase.jdbc3.jdbc.SybStatement.nextResult(Unknown Source)
    at com.sybase.jdbc3.jdbc.SybStatement.executeLoop(Unknown Source)
    at com.sybase.jdbc3.jdbc.SybStatement.execute(Unknown Source)
    at com.sybase.jdbc3.jdbc.SybStatement.execute(Unknown Source)
    at PlayProcsExecutor.main(PlayProcsExecutor.java:44)

A: Take a look at flyaway, a java tool for db migration and version control.
Another alternative is liquibase but I find it more heavyweight than flyaway.
Flyaway can be embedded in your application and run on startup or can be triggered via ant/maven/gradle etc.

A: I don't think you can run the script with a single execute.
Try splitting the string for every "go" and running java.sql.Statement.execute(...) for each substring. Note, I think you need to remove "go" from what is executed.
eg
stmt.execute("use ams_trading");
stmt.execute("if object_id('#batch_mdl_list') is not null drop table #batch_mdl_list");
stmt.execute("create table #batch_mdl_list (id_batch int not null, id_mdl int not null)");
...


text:
Q: How do i use JOIN with a get_where clause in CodeIgniter I'm trying to get the data from two tables after an "Open" button is clicked from previous table UI by sending an Id.
e.g.
<a name="Open" href="<?php echo base_url('welcome/WellProfile/'.$post->Id) ?>">

(https://imgur.com/6IU1Tfo)
So I have two tables - namely "WellDataA" and "WellDataB" , I want to get the data where WellDataB data matches with the WellDataA by WellName(column).
Example:

WellDataA:
Id   Platform  WellName
.
.
4      ZE          ZE-A
5      ZE          ZE-B
6      ZE          Ze-B
.
.

WellDataB:
Id     WellName     CompleteDate
1        ZE-A           12/3
2        ZE-B           14/5
3        ZE-C           20/6

This is how my query so far, but it ended up error
public function get_news_by_id($Id = 0)
{
        if ($Id === 0)
        {
            $query = $this->db->get('WellDataA');
            return $query->result_array();
        }
         $this->db->select('*');
         $this->db->from('WellDataA');
         $this->db->join('WellDataB','WellDataA.WellName =
         WellDataB.WellName','INNER');
        $query = $this->db->get_where('WellDataA', array('Id' => $Id));
        return $query->row_array();
}

I expect the output would show ZE, ZE-A, 12/3 when "Open" button is clicked on ZE-A. But the actual output is ZE, ZE-A only. Thank you so much in advance!:)

A: Firstful I am sorry if my solution won't be a good one,
but I suggest you change the structure of your tables to this:
WellDataA:
Id   Platform  WellDataB
.
.
4      ZE          1
5      ZE          2
6      ZE          3
.
.

WellDataB:
Id     WellName     CompleteDate
1        ZE-A           12/3
2        ZE-B           14/5
3        ZE-C           20/6

Since I assume that the used model is relational, one thing must first achieved is to make the tables all relational. Instead of connecting WellDataA and WellDataB with the Id from WellDataB inside WellDataA.

A: Try this, your issue is in get_where() so, i removed it and rewrite it
public function get_news_by_id($Id = 0)
{
    if ($Id === 0)
    {
        $query = $this->db->get('WellDataA');
        return $query->result_array();
    }
    $this->db->select('a.Id,a.Platform,a.WellName,b.Id,b.CompleteDate');
    $this->db->from('WellDataA a');
    $this->db->join('WellDataB b','a.WellName = b.WellName','INNER');  //changes
    $this->db->where('b.Id',$Id); //changes
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        return $query->row_array();
    }else{
        return array();
    }
}

A: I think you just need to remove some code. Just try this code
public function get_news_by_id($Id = 0)
{
        if ($Id === 0)
        {
            $query = $this->db->get('WellDataA');
            return $query->result_array();
        }
         $this->db->join('WellDataB','WellDataA.WellName =
         WellDataB.WellName','INNER');
        $query = $this->db->get_where('WellDataA', array('Id' => $Id));
        return $query->row_array();
}


text:
Q: Updating columns if not null I have a table 'Contacts' with a bunch of rows and columns that looks a bit like this:
ID |FirstName|LastName|Addr1|Addr2      |Phone   |...|
1  |Anna     |Johnson |123  |Fake street|12345678|...|
2  |Bob      |Smith   |234  |Foo Ave    |23456789|...|

Now Anna has moved and I want to update her address. My system outputs a row with the Contacts rowtype where the PK and updated columns have a value, everything else is null.
declare
 update_row Contacts%rowtype;
begin
 update_row := (1,null,null,987,Bar Street,null,null);

What I want to do now is keep the original row of Contacts and just update the values that are not null in update_row.
What I essentially want to do is this:
if update_row.FirstName is not null then Contacts.FirstName := update_row.FirstName;
if update_row.LastName is not null then Contacts.LastName := update_row.LastName;
if update_row.Addr1 is not null then Contacts.Addr1 := update_row.Addr1;
if update_row.Addr2 is not null then Contacts.Addr2 := update_row.Addr2;
...

or something to that extent but without having to explicitly check every single column value.
Is there a solution that looks something like this?:
merge update_row into Contacts where update_row is not null and ID = 1

A: You could write a query that checks each input field and only replaces if a non-null value is given.
The following would work for Oracle, with the NVL function (in mysql, use COALESCE, and so on).
UPDATE CONTACTS
SET
    FIRST_NAME = NVL(?, FIRST_NAME),
    LAST_NAME  = NVL(?, LAST_NAME),
    ADDR1      = NVL(?, ADDR1),
    ADDR2      = NVL(?, ADDR2),
    PHONE      = NVL(?, PHONE)
WHERE ID = ?

A: Here is a concept how you can achieve it with package in a dynamic way.
CREATE TABLE contact (
  id      NUMBER,
  cust_id NUMBER,
  line1   VARCHAR2(100),
  line2   VARCHAR2(100)
);

CREATE OR REPLACE PACKAGE pkg_test IS

  /*
  * Variables for contact table.
  */
  gv_contact1 contact%ROWTYPE;
  gv_contact2 contact%ROWTYPE;

  /* Do overwrite for Contact table
   * pi_contact1.ColumnName is overwitten when pi_contact2.ColumnName IS NOT NULL
   *
   * @param pi_contact1     Contact record which is overwritten
   * @param pi_contact2     Contact record from wich data are copied
   */
  FUNCTION overwriteContactIfNull(
    pi_contact1 contact%ROWTYPE,
    pi_contact2 contact%ROWTYPE
  )
  RETURN contact%ROWTYPE;

END pkg_test;
/

CREATE OR REPLACE PACKAGE BODY pkg_test IS

  /* List of columns in a table
   *
   * @param pi_tableName     Table name
   */
  FUNCTION columns_(
      pi_tableName       VARCHAR2
  )
  RETURN SYS.ODCIVARCHAR2LIST
  AS
    lv_ColumNames SYS.ODCIVARCHAR2LIST;
  begin
    SELECT CAST (
             MULTISET
                  (
                    SELECT c.column_name
                      FROM user_tab_columns c
                     WHERE c.table_name = pi_tableName
                  ) AS SYS.ODCIVARCHAR2LIST
                )
      INTO lv_ColumNames
      FROM dual;

    RETURN lv_ColumNames;
  END columns_;

  /* Do overwirte for a specific table
   * gv_#TableName1.ColumnName is overwitten when gv_#TableName2.ColumnName IS NOT NULL
   *
   * @param pi_tableName     Table name
   */
  PROCEDURE overwriteIfNull(
    pi_tableName    VARCHAR2
  )
  AS
    lc_bodyTemplate CONSTANT CLOB :=
    'BEGIN'                                                                            || CHR(10) ||
    '  IF pkg_test.gv_#TableName2.#ColumnName IS NOT NULL THEN'                        || CHR(10) ||
    '    pkg_test.gv_#TableName1.#ColumnName := pkg_test.gv_#TableName2.#ColumnName; ' || CHR(10) ||
    '  END IF;'                                                                        || CHR(10) ||
    'END;';

    lv_ColumNames SYS.ODCIVARCHAR2LIST;

    lv_body CLOB;
  BEGIN

    lv_ColumNames := columns_(pi_tableName => 'CONTACT');

    FOR i IN 1..lv_ColumNames.COUNT
    LOOP
      lv_body := lc_bodyTemplate;
      lv_body := REPLACE(lv_body, '#TableName' , pi_tableName);
      lv_body := REPLACE(lv_body, '#ColumnName', lv_ColumNames(i));
      EXECUTE IMMEDIATE lv_body;
    END LOOP;

  END overwriteIfNull;

  /* Do overwrite for Contact table
   * pi_contact1.ColumnName is overwitten when pi_contact2.ColumnName IS NOT NULL
   *
   * @param pi_contact1     Contact record which is overwritten
   * @param pi_contact2     Contact record from wich data are copied
   */
  FUNCTION overwriteContactIfNull(
    pi_contact1 contact%ROWTYPE,
    pi_contact2 contact%ROWTYPE
  )
  RETURN contact%ROWTYPE
  AS
  BEGIN
    gv_contact1 := pi_contact1;
    gv_contact2 := pi_contact2;

    overwriteIfNull(pi_tableName => 'CONTACT');

    RETURN gv_contact1;
  END overwriteContactIfNull;

END pkg_test;
/

And this is example of call
DECLARE
  lv_contact1 contact%ROWTYPE;
  lv_contact2 contact%ROWTYPE;
BEGIN

  lv_contact1.line1 := 'Line1';
  lv_contact1.line1 := 'Line2';

  lv_contact2.line2 := 'NewLine2';

  lv_contact1 := pkg_test.overwriteContactIfNull(
                     pi_contact1 => lv_contact1,
                     pi_contact2 => lv_contact2
                 );

  dbms_output.put_line('lv_contact1.line1:' || lv_contact1.line1);
  dbms_output.put_line('lv_contact1.line2:' || lv_contact1.line2);
END;
/


text:
Q: Blank page on npm start react I'm new to React and I'm creating a React app
which on npm start it's returning a blank page.
Below is :
Here's my index.js
import React from "react";
import ReactDOM from 'react-dom';

import App from '../src/App';

ReactDOM.render(<App />,
document.getElementById('root'));

App.js
import React from 'react'
import { BrowserRouter as Router, Switch, Route
} from 'react-router-dom';

const App = () => {
  return (
      <div>
        Ecommerce
      </div>
  )
}

export default App;

How do I fix this?

A: Make sure you have installed react-router-dom:
npm i react-router-dom

A: I had this problem until just now I turned off my VPN.

*

*Turn off VPN

*restart your app (npm start)

*let us know if it works


text:
Q: Python: Attribute Error(NoneType object has no attribute split) I am trying to make some approximations discard.
The function given below is throwing attribute error. What might be the issue? Kindly help me if possible.
def calculate_tps(filename,identity):
  ##command='tshark -r %s -R -T pdml diameter'
  first_time = None
  last_time=None
  tshark='tshark -r %s -R \'(diameter.Destination-Host==%s)&& (diameter.CC-Request-Type==3)\' -T pdml'% (filename,identity)
  time = None
  req = 0
  for line in os.popen(tshark, 'r'):
    m=pattern.search(line)
    if m:
      #print m.group(1)
      if m.group(1) == 'timestamp':
    time=m.group(2)
    if not first_time:
      first_time=time
      elif m.group(1) == 'diameter.Session-Id':
        req +=1
    if(req % 100) ==0:
      print 'processed 1000 requests req number %s ' % req

  # making some approximations discard ms
  first = long(first_time.split('.').pop(0))
  last =  long(time.split('.').pop(0))
  time_elapsed = first -last
  print "%s requests in %s seconds, tps = %s " % ( req, time_elapsed, req/time_elapsed)

Here is the full code. I am trying to calculate number of request per second using tshark.
#!/usr/bin/python
import re
import sys
import commands

    import os
    import time

    pattern = re.compile('<field name="(timestamp|diameter.Session-Id)".*value="([^"]+)')

    from optparse import OptionParser
    def parse_options():
      parser = OptionParser()
     # parser.add_option("-f", "--file", dest="filename",
     #                 help="input pcap file", metavar="FILE")
      parser.add_option("-i", "--identity", dest="identity",
                      help="diameter identity to filter on", metavar="IDENTITY")

      opts, args = parser.parse_args()
      return opts, args

    def calculate_tps(filename,identity):
      ##command='tshark -r %s -R -T pdml diameter'
      first_time = None
      last_time=None
      tshark='tshark -r %s -R \'(diameter.Destination-Host==%s)&& (diameter.CC-Request-Type==3)\' -T pdml'% (filename,identity)
      time = None
      req = 0
      for line in os.popen(tshark, 'r'):
        m=pattern.search(line)
        if m:
          #print m.group(1)
          if m.group(1) == 'timestamp':
        time=m.group(2)
        print 'time is %s' % time
        if not first_time:
          first_time=time
          prin
          elif m.group(1) == 'diameter.Session-Id':
            req +=1
        if(req % 100) ==0:
          print 'processed 1000 requests req number %s ' % req

      # making some approximations discard ms
      first = long(first_time.split('.').pop(0))
      last =  long(time.split('.').pop(0))
      time_elapsed = first -last
      print "%s requests in %s seconds, tps = %s " % ( req, time_elapsed,
      req/time_elapsed)

    def main():
      global options
      options, args = parse_options()
      if len(args) < 1:
        print >>sys.stderr, "missing pcap file.Please specify the pcap"
        sys.exit(1)
      #print options.identity

      start_time = time.time()
      calculate_tps(args.pop(0), options.identity)
      end_time = time.time()
      print 'completed in %s', (end_time - start_time)

    if __name__ == '__main__':
       main()

A: When you make the calls here:
first = long(first_time.split('.').pop(0))
last =  long(time.split('.').pop(0))

You've assumed that each of these is a string.  They appear to not have been reassigned during your loop over the file contents, suggesting that your matches are not taking place.  You could wrap those in a conditional check with something like this:
if None in (first_time, time):
  print "Uh oh, one of first_time or time is None - ", first_time, time

That would give you an indicator of the problem at the very least.

A: This is because your first and last are not string. So there is no attribute split of the type.
So if you need split attribute, you better change them to string type.


text:
Q: c# How to do automatic check when the table is inserted a new row I have table messages and I linked it it with DataGridView and I want him to be updated automatically if new row is inserted in table by other pc, i can use refresh button with following code source :
datagridview1.update();
datagridview1.refresh();

or i can use thread with interval of 1000 ms ,
but i want more Instantaneous method like socket in network, any ideas ?

A: According to MSDN
DataGridView.Refresh

Forces the control to invalidate its client area and immediately redraw itself and any child controls.

DataGridView.Update

Causes the control to redraw the invalidated regions within its client area.

Since Refresh and Update just redraw your DataGridView, this won't get you too far, if you don't have any cyclic checking on your DataSource (f.e. your database).

A: I assume your database is SQL Server. Then, you can use the SQL Server Service Broker (SSB), so that your datagrid updates automatically on DB changes.
You should take a look at this project on Code Project. Using the ServiceBrokerUtility, it's easy to refresh your object set not only once, but automatically on each update that occurs in the database.


text:
Q: extjs 4 line chart rendering problems I am having trouble with extjs rendering the line chart below. Specifically, the last six values are null which are (correctly) not shown on the series line but (incorrectly) have a marker dot displayed for them (see top right of the image below).

I am pulling the graph data from a database as json:
// data store fields
Ext.define('Graphs', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'the_quota',     type: 'int'},
        {name: 'count_pt_year', type: 'int'},
        {name: 'date_string',   type: 'string'}
    ]
});

// get the graph data
var graphStore = Ext.create('Ext.data.Store', {
    model: 'Graphs',
    proxy: {
        type: 'ajax',
        url: 'sqlRequest.jsp?queryName=events_getGraph',
        timeout: 160000,
        reader: 'json'
    },
    autoLoad:false
});

If I change the query to return these null values as blanks instead ('') then the json reader converts them to zeros and the values display as zero along the bottom of the graph with a series line, which is worse then having the markers plastered to the ceiling without a series line.
I haven't been able to find any config option in Ext.chart.Series to hide null values on the graph. Nor have I been able to find a config option in Ext.data.Store to return blanks as blanks and not "0".
Looking for some other workaround.
Or has anyone resolved these issues from within the library itself (ext-all.js)?

A: There's a config option under Ext.data.Field called useNull. If the data received cannot be parsed into a number, null will be used instead. As of right now I can't recall if that alone will fix the problem, and I have a memory of once using a custom convert function that went something like this:
convert: function(value){
    if(typeof value !=== 'number') // or other similar conversion
        return undefined;
    return value;
}

If this doesn't work, you may need to customize your store/reader to completely exclude records containing the undesirable null value.
EDIT - Using useNull looks like this: {name: 'someName', type: 'int', useNull: true}


text:
Q: Java pdfbox library for Rectangle Rotation Trying to rotate the rectangle using pdfbox libraries based on fabric json, but x-co-ordinate & y-co-ordinate are not showing in correct position.
code below:
public void drawRectangle(PDPageContentStream contentStream, PDPage page, JSONObject props) throws IOException {

        String originX = (String) props.get("originX");
        String originY = (String) props.get("originY");
        Double left = (Double) props.get(originX);
        Double top = (Double) props.get(originY);
        Double width = (Double) props.get("width");
        Double hight = (Double) props.get("height");

        String fillColor = (String) props.get("fill"); // "#B3B3B3";
        String strokeColor = null;
        if (hight != 1.0) {
            strokeColor = (String) props.get("stroke"); // "#000000";
        }
        Double strokeWidth = (Double) props.get("strokeWidth"); // 0.0f;

        String strokeLineCap = (String) props.get("strokeLineCap"); // "butt";
        String strokeLineJoin = (String) props.get("strokeLineJoin"); // "miter";
        Double strokeMitterLimit = (Double) props.get("strokeMiterLimit");

        String fillRule = (String) props.get("fillRule"); // "nonzero";
        contentStream.setNonStrokingColor(Color.decode(fillColor));
        if (hight != 1.0) {
            contentStream.setStrokingColor(Color.decode(strokeColor));
        }
        contentStream.setLineWidth(strokeWidth.floatValue());
        contentStream.setLineCapStyle(
                "butt".equalsIgnoreCase(strokeLineCap) ? 0 : ("round".equalsIgnoreCase(strokeLineCap) ? 1 : 2));
        contentStream.setLineJoinStyle(
                "miter".equalsIgnoreCase(strokeLineJoin) ? 0 : ("round".equalsIgnoreCase(strokeLineCap) ? 1 : 2));
        contentStream.setMiterLimit(strokeMitterLimit.floatValue());

        Double scaleX = (Double) props.get("scaleX"); // 1.0f;//must be minimum 1
        if (scaleX <= 1) {
            scaleX = (Double) 1.0;
        }
        Double scaleY = (Double) props.get("scaleY"); // 1.0f;// must be minimum 1
        if (scaleY <= 1) {
            scaleY = (Double) 1.0;
        }
        double angle = (double) props.get("angle"); // 0.0d;

        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;

        contentStream.transform(Matrix.getTranslateInstance(tx, ty));
        contentStream.transform(Matrix.getRotateInstance(Math.toRadians(360-angle), 0, 0));
        contentStream.transform(Matrix.getTranslateInstance(-tx, -ty));

        contentStream.addRect(left.floatValue(), page.getMediaBox().getHeight()-top.floatValue() - hight.floatValue(),
                   width.floatValue(), hight.floatValue());

        if ("nonzero".equals(fillRule)) {
            contentStream.fillAndStroke();
        } else {
            contentStream.fillAndStrokeEvenOdd();
        }
}

my sample fabric json:
{
        "type": "rect",
        "pos": 3,
        "tag": "",
        "version": "4.3.1",
        "originX": "left",
        "originY": "top",
        "left": 550.6,
        "top": 632.35,
        "width": 71.26,
        "height": 99.51,
        "fill": "#B3B3B3",
        "stroke": "#000000",
        "strokeWidth": 0.0,
        "strokeLineCap": "butt",
        "strokeDashOffset": 0.0,
        "strokeLineJoin": "miter",
        "strokeMiterLimit": 4.0,
        "scaleX": 1.0,
        "scaleY": 1.0,
        "angle": 111.31,
        "flipX": false,
        "flipY": false,
        "opacity": 1.0,
        "visible": true,
        "backgroundColor": "",
        "fillRule": "nonzero",
        "paintFirst": "fill",
        "globalCompositeOperation": "source-over",
        "skewX": 0.0,
        "skewY": 0.0,
        "lockMovementX": false,
        "lockMovementY": false,
        "lockScalingX": false,
        "lockScalingY": false,
        "lockUniScaling": false,
        "lockRotation": false,
        "lockObject": false,
        "fillColor": {
            "id": 0,
            "cyan": 0,
            "magenta": 0,
            "yellow": 0,
            "black": 30,
            "tint": 100.0,
            "shade": 0.0,
            "name": "C=0 M=0 Y=0 K=30",
            "isTransparent": false,
            "isSpotColor": false
        },
        "strokeColor": {
            "id": 0,
            "cyan": 0,
            "magenta": 0,
            "yellow": 0,
            "black": 100,
            "tint": 100.0,
            "shade": 0.0,
            "name": "C=0 M=0 Y=0 K=100",
            "isTransparent": false,
            "isSpotColor": false
        },
        "rx": 0.0,
        "ry": 0.0,
        "absolutePositioned": false,
        "inverted": false
    }

and tried different ways as mentioned in stackoverflow, nothing seems to be working. I appreciate any help on that.


text:
Q: How to handle many bootstrap modals on a single html page I would have 10 bootstrap buttons on a single html page.
Each button opens a ootstrap modal filled with a html fragmen via an ajax request.

$('#myModal').modal();

Should I create 10 different divs with 10 different ids? Or even 10 different instances?
 var dialogInstance1 = new BootstrapDialog({
            title: 'Dialog instance 1',
            message: 'Hi Apple!'
        });

or
should I create ONE dialog?
I would expect kind of caching problems when I open modal1, then just when I open modal2 I see still for some miliseconds modal1 html fragment from a prvious ajax request.
And how should I create those modals? The samples should this:
        $('#myModal').modal();

and the instantiation? This is very confusing.
Can someone please share his experience how to approach with many bootstrap modals?

A:
I would expect kind of caching problems when I open modal1, then just when I open modal2 I see still for some miliseconds modal1 html fragment from a prvious ajax request.

Assuming you're referring to data-remote's caching, you will probably be able to disable that in Bootstrap v3.2.0 (see https://github.com/twbs/bootstrap/pull/13183/ ).
However, I'd still recommend against using data-remote since it doesn't give you much control. It:

*

*doesn't provide or easily let you do any error handling

*doesn't give any "loading..." indication

*forces you have to generate modal HTML on the server side (as opposed to, e.g., returning JSON from the server and using client-side templating)

IMO, you should:

*

*include just one instance of the blank modal markup

*setup your own click event handlers on the buttons that summon your modal

*initiate the AJAX request in your click event handler

*use client-side templating to generate a corresponding modal using the results of the request

*use $(...).modal() or $(...).modal('show') (depends on how your templating works) to show the modal after the templating completes


text:
Q: Custom Filter AdminJS (Component + Action) I am trying to create a custom filter. I am on a table and want to sort according to fields on another table. ManyToMany relation between tables.
I also need to create a custom filter component, with matching design.
After a day of work, my working solution is in the answer, so if you have the same issue, it will save you time :)

A: Here is my solution :
I linked the component from the ResourceOptions in the components section within a custom component who had already a customer list bundle :
filter: AdminJS.bundle("../../components/generic/filter/FilterSublist"),

Here is the custom style :

//style so your custom components looks like the basic AdminJS component
const customStyles = {
  menu: (provided, state) => ({
    ...provided,
    borderRadius: 0,
    backgroundColor: "#343F87",
  }),

  control: (provided, state) => ({
    ...provided,
    backgroundColor: "#343F87",
    borderRadius: 0,
    border: '1px solid #525C99',
  }),

  option: (provided, state) => ({
    ...provided,
    '&:hover': {
      backgroundColor: '#2E3974',
    },
    backgroundColor: "#343F87",
  }),
}

Here is the component :

import {BasePropertyComponent, BasePropertyProps, ApiClient, useRecord} from "adminjs";
import AsyncSelect from 'react-select/async';
import React, {useState, useEffect} from "react";

const FilterSublist = (props: BasePropertyProps) => {
  const [values, setValues] = useState<Array<{label: string, value: any}>>([]);
  const [defaultOptions, setDefaultOptions] = useState<Array<{label: string, value: any}>>([]);
  const api = new ApiClient()

  useEffect(() => {handleGetDefaultValues()}, [])

  const handleGetDefaultValues = async () => {
    const searchResults = await api.searchRecords({resourceId: "ServiceProviderAreaOfAction", query: ""})
    const filteredResults = searchResults.filter(r => r.params.id !== Number(values))
    setDefaultOptions(filteredResults.map(v => ({label: v.title, value: v.params.id})))
  }

  const handleSearch = async (inputValue: string, callback: (options: Array<{ label: string, value: any }>) => void) => {
    const searchResults = await api.searchRecords({resourceId: "ServiceProviderAreaOfAction", query: inputValue})
    const filteredResults = searchResults.filter(r => !values.map(v => Number(v.value.id)).includes(Number(r.params.id)))
    callback(filteredResults.map(v => ({label: v.title, value: v.params.id})))
  }

  //Store values in props.filter so they are sent with all the filters
  const handleChange = (a: Array<{label: string, value: any}>) => {
    setValues(a ? a : [])
      // @ts-ignore
      props.onChange(props.property.propertyPath, (a ? a.map(e => e.value).join(',') : undefined))
  }

  return (

Area of action

      {/* @ts-ignore */}
      <AsyncSelect className="AsyncSelectBlue" isMulti defaultOptions={defaultOptions} value={values} onChange={handleChange} loadOptions={handleSearch} styles={customStyles}/>

  )
}

export default FilterSublist

In the ResourceOptions again, I used a custom handler to list actions, and in that handler, I detected the custom filter, transformed it to an array of id, then deleted the custom filter field, let the normal filter do his job, and filtered the result with the array of id.
I hope it helps :)


text:
Q: What is the design consideration of setting default worker thread count as (availableProcessors * 2) in Netty? availableProcessors * 2
Why is it and does it has some special design consideration here?
Is it a value somehow got from performance turning experience?
Thanks!

A: Yes it is from experience and often a good starting point. How many you really need depends a bit on how many concurrent connections you have and what are the processing times within your ChannelHandlers.
The best way to find out is to attach a profiler and check how busy the Threads are etc.


text:
Q: How can I use different proguard files in different flavors or for different build types? I need to make different flavors for test libraries. Why? Well, I want project to be fully secured so I wanna minifying to be enabled all the time(even for debug build type).
While making tests I'm using different classes from project,
so I decided to change proguard files using flavor. It looks like something this :
android {
    ...
    buildTypes {
        release {
            minifyEnabled true
            testProguardFile 'test-proguard-rules.pro'
        }
        debug {
            minifyEnabled true
            testProguardFile 'test-proguard-rules.pro'
        }
    }
    ...
    productFlavors{
        forTest{
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules1.pro', 'debug-rules.pro'
        }
        forRelease{
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'debug-rules.pro'
        }
   }
}

And proguard-rules* files
proguard-rules:
-dontwarn blablabla.**
-dontwarn blabla.**
-keep class bla.** { *; }

proguard-rules1:
-dontshrink
-dontobfuscate
-dontwarn

But this wasn't helpful for me. I want to run tests without obfuscation. Flavors doesn't have such param as minifyEnabled so I try to find any solution. So any suggestions about resolving an issue? May be someone had the same problem and find another solution (not using flavors) ?

A: After a whole day messing with this I found the following works:
buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

productFlavors {
    flavorA {
        applicationIdSuffix ".a"
        proguardFile 'flavorA_rules.pro'
    }
    flavorB {
        applicationIdSuffix ".b"
    }

}

More info: Include additional configurations


text:
Q: How do I set the HTTP request header on a webservice reference? Here is the problem...
I have a webservice which works great with the JAVA code...
package com.mypackage.myproject;

 public class ExecuteGetOrder {

public static void main(String [ ] args)
{
     try {

        runGetOrder();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void runGetOrder() throws Exception
 {

        GetOrderDataInterface data = new GetOrderDataInterfaceProxy().getGetOrderDataInterface();
        ((org.apache.axis.client.Stub)data)._setProperty(org.apache.axis.client.Call.USERNAME_PROPERTY, "ent=,user=UserName");
        ((org.apache.axis.client.Stub)data)._setProperty(org.apache.axis.client.Call.PASSWORD_PROPERTY, "password");
        String RtrnDataXML = data.OrderInfo("OrderNumber");
        System.out.println(RtrnDataXML);

}

}

The Raw request looks like this...
POST http://win-bpqhaq6l0jt:8008/oms/services/GetOrderData HTTP/1.0
Content-Type: text/xml; charset=utf-8
Accept: application/soap+xml, application/dime, multipart/related, text/*
User-Agent: Axis/1.4
Host: win-bpqhaq6l0jt:8008
Cache-Control: no-cache
Pragma: no-cache
SOAPAction: ""
Content-Length: 366
Authorization: Basic ZW50PSx1c2VyPUEyTENNQWRtaW46cGFzc3dvcmQ=

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ammoOrderInfo xmlns="http://a2lcm.rhinotechnology.com/"><order xmlns="">OrderNumber</order></OrderInfo></soapenv:Body></soapenv:Envelope>

Now I want to do this same thing in a VB.NET windows application. First I added the service reference, but when I try to use the class generated with this code...
    Dim OrderService As getOrderData.GetOrderDataInterfaceClient = New getOrderData.OrderDataInterfaceClient()
    Dim returnedXMl = OrderService.OrderInfo("Order")

I get back this...
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
WWW-Authenticate: Basic host=10.20.100.7
Content-Type: text/html;charset=utf-8
Content-Length: 948
Date: Fri, 30 May 2014 21:25:05 GMT

<title>JBossWeb/2.0.1.GA - Error report</title>
HTTP Status 401 -

type Status report

message

  description This request requires HTTP authentication ().

JBossWeb/2.0.1.GA

So the question is how do I set the HTTP Authorization: on the request when made with...
Dim OrderService As getOrderData.GetOrderDataInterfaceClient = New GetOrderData.OrderDataInterfaceClient()
Dim returnedXMl = OrderService.OrderInfo("Order")

A: So the solution for all trying to Basic authenticate with JBoss web services...
1) Add the following class (Code in vb)
Imports System.ServiceModel.Dispatcher

Imports System.ServiceModel.Channels

Imports System.ServiceModel.Description

Imports System.ServiceModel.Configuration

Imports System.Configuration

Public Class HttpUserAgentMessageInspector
Implements IClientMessageInspector

Private Const USER_AGENT_HTTP_HEADER As String = "Authorization"

Private m_userAgent As String

Public Sub New(ByVal userAgent As String)
    MyBase.New()
    Me.m_userAgent = userAgent
End Sub

Public Sub AfterReceiveReply(ByRef reply As System.ServiceModel.Channels.Message, ByVal correlationState As Object) Implements IClientMessageInspector.AfterReceiveReply

End Sub

Public Function BeforeSendRequest(ByRef request As System.ServiceModel.Channels.Message, ByVal channel As System.ServiceModel.IClientChannel) As Object Implements IClientMessageInspector.BeforeSendRequest
    Dim httpRequestMessage As HttpRequestMessageProperty
    Dim httpRequestMessageObject As Object
    If request.Properties.TryGetValue(HttpRequestMessageProperty.Name, httpRequestMessageObject) Then
        httpRequestMessage = CType(httpRequestMessageObject, HttpRequestMessageProperty)
        If String.IsNullOrEmpty(httpRequestMessage.Headers(USER_AGENT_HTTP_HEADER)) Then
            httpRequestMessage.Headers(USER_AGENT_HTTP_HEADER) = Me.m_userAgent
        End If
    Else
        httpRequestMessage = New HttpRequestMessageProperty
        httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, Me.m_userAgent)
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage)
    End If
    Return Nothing
End Function
End Class
Public Class HttpUserAgentEndpointBehavior
Implements IEndpointBehavior

Private m_userAgent As String

Public Sub New(ByVal userAgent As String)
    MyBase.New()
    Dim headerBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(userAgent)
    Dim headerValue As String = ("Basic " + Convert.ToBase64String(headerBytes))
    Me.m_userAgent = headerValue
End Sub
#Region "IEndpointBehavior Members"

Public Sub AddBindingParameters(ByVal endpoint As ServiceEndpoint, ByVal bindingParameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IEndpointBehavior.AddBindingParameters

End Sub

Public Sub ApplyClientBehavior(ByVal endpoint As ServiceEndpoint, ByVal clientRuntime As System.ServiceModel.Dispatcher.ClientRuntime) Implements IEndpointBehavior.ApplyClientBehavior
    Dim inspector As HttpUserAgentMessageInspector = New HttpUserAgentMessageInspector(Me.m_userAgent)
    clientRuntime.MessageInspectors.Add(inspector)
End Sub

Public Sub ApplyDispatchBehavior(ByVal endpoint As ServiceEndpoint, ByVal endpointDispatcher As System.ServiceModel.Dispatcher.EndpointDispatcher) Implements IEndpointBehavior.ApplyDispatchBehavior

End Sub

Public Sub Validate(ByVal endpoint As ServiceEndpoint) Implements IEndpointBehavior.Validate

End Sub
#End Region
End Class
Public Class HttpUserAgentBehaviorExtensionElement
Inherits BehaviorExtensionElement

Public Overrides ReadOnly Property BehaviorType As Type
    Get
        Return GetType(HttpUserAgentEndpointBehavior)
    End Get
End Property

Protected Overrides Function CreateBehavior() As Object
    Return New HttpUserAgentEndpointBehavior(UserAgent)
End Function

<ConfigurationProperty("userAgent", IsRequired:=True)> _
Public Property UserAgent As String
    Get
        Return CType(Me("userAgent"), String)
    End Get
    Set(value As String)
        Me("userAgent") = value
    End Set
End Property
End Class

2) Add the following XML code to your app.config between the system.serviceModel tags.

  <behaviors>
         <endpointBehaviors>
        <behavior name="LegacyServiceEndpointBehavior">
          <httpUserAgent userAgent="[[[myusername:password]]]" />
        </behavior>
      </endpointBehaviors>
     </behaviors>
     <extensions>
      <behaviorExtensions>
         <add name="httpUserAgent" type="  [[[myNamespace]]].HttpUserAgentBehaviorExtensionElement, [[[myProjectName]]], Version=1.0.0.0, Cultu re=neutral, PublicKeyToken=null" />
       </behaviorExtensions>
       </extensions>
      </system.serviceModel>

3) Change the highlighted text to your namespace and project respectively.
4) Add the following text surrounded by [[[ ]]]to the end of the endpoint address. This part will need done to each service.
 <endpoint address="http://[[[ipAddress]]]/Location/GetOrderData"
            binding="basicHttpBinding" bindingConfiguration="RLCM.GetOrderDataInterfaceSoapBinding"
            contract="getOrderData.GetOrderDataInterface" name="GetOrderDataImplPort" [[[behaviorConfiguration="LegacyServiceEndpointBehavior"]]]/>

5) Now you should be able to use the code like this…

  Dim OrderService As getOrderData.GetOrderDataInterfaceClient = New getOrderData.GetOrderDataInterfaceClient()
  Dim returnedXML = OrderService.orderInfo("OrderNumber") and be authorized by the JBoss server and get back return data.


text:
Q: Can a PHP script start another PHP script and exit? How can a PHP script start another PHP script, and then exit, leaving the other script running?
Also, is there any way for the 2nd script to inform the PHP script when it reaches a particular line?

A: Here's how to do it. You tell the browser to read in the first N characters of output and then close the connection, while your script keeps running until it's done.
<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(); // optional
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Will not work
flush();            // Unless both are called !

// At this point, the browser has closed connection to the web server

// Do processing here
include('other_script.php');

echo('Text user will never see');
?>

A: You can effectively achieve this by forking and then calling include or require.
parent.php:
<?php

    $pid = pcntl_fork();
    if ($pid == -1) {
        die("couldn't fork");
    } else if ($pid) { // parent script
        echo "Parent waiting at " . date("H:i:s") . "\n";
        pcntl_wait($status);
        echo "Parent done at " . date("H:i:s") . "\n";
    } else {
        // child script
        echo "Sleeper started at " . date("H:i:s") . "\n";
        include('sleeper.php');
        echo "Sleeper done at " . date("H:i:s") . "\n";
    }

?>

sleeper.php:
<?php
sleep(3);
?>

Output:

$ php parent.php
Sleeper started at 01:22:02
Parent waiting at 01:22:02
Sleeper done at 01:22:05
Parent done at 01:22:05

However, forking does not inherently allow any inter-process communication, so you'd have to find some other way to inform the parent that the child has reached the specific line, like you asked in the question.

A: Here's a shot in the dark: you could try using php's OS execution functions with &.
exec("./somescript.php &");

Additionally, if that doesn't work, you can try
exec("nohup ./somescript.php &");

Edit: nohup is a POSIX command to ignore the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. The HUP (hangup) signal is by convention the way a terminal warns depending processes of logout.

A: Would pcntl_fork() do something similar to what you're ultimately trying to accomplish? http://www.php.net/manual/en/function.pcntl-fork.php

A: If you don't want to build the pcntl extension, then a good alternative is to use proc_open().
http://www.php.net/manual/en/function.proc-open.php
Use that together with stream_select() so your PHP process can sleep until something happens with the child process you created.
That will effectively create a process in the background, without blocking the parent PHP process. You PHP can read and write to STDIN, STDOUT, STDERR.
To make the browser complete loading (stop the load progress indicator) then you can use what Milan Babuškov mentioned.
The key to making the browser think the HTTP request is complete, is to send it the content length. To do this you can start buffering the request, then flush it after you send the Content-Length header.
eg:
<?php

ob_start();

// render the HTML page and/or process stuff

header('Content-Length: '.ob_get_length());
ob_flush();
flush();

// can do more processing

?>

A: You can create a request and close the connection right after it is done being written to.
Checkout the code in http://drupal.org/project/httprl as can do this (non-blocking request). I plan on pushing this lib to github once I get it more polished; something that can be ran outside of drupal. This should do what your looking for.


text:
Q: How to obtain deg instead ° with siunitx package? I'm using the following command to write a phisical quantity in my report:
\si[per-mode = symbol]{\degree\per\second

I obtain: °/s but I want: deg/s.
How can I solve this problem?

A:
You can use \deg instead.
You can choose to use / instead of ^{-1} for 'per' with the option [per-mode=symbol] which you can make a package option, as in \usepackage[per-mode=symbol]{siunitx} or pass to a single call of \SI or \si
\documentclass{article}

\usepackage{siunitx}

\begin{document}
    \SI{1}{\deg\per\second}
    \SI[per-mode=symbol]{1}{\deg\per\second}
\end{document}

If you want to redefine \degree across the document you can use
\DeclareSIUnit{\degree}{deg}

in your preamble.


text:
Q: Using slideUp() and remove() on more than one DIV I have the following code which should find all the DIVs, except the first, within my table, slide them up and then remove them!
$("#myTable div:not(:first)").slideUp('slow', function() {
$(this).remove();
});

Now it successfully applies this to the second DIV but to no other.
However, if I use
$("#myTable div:not(:first)").slideUp('slow').remove();

it removes all the DIVs after the first correctly.  However, the slideUp animation does not run.
Any ideas?
Thanks

A: Yep - you need to remove AFTER the slide up has completed. Like so:
$("#myTable div:not(:first)").slideUp('slow', function(){ $(this).remove(); } );

A: It appears to me that your first example should work. See this fiddle as an example of that: http://jsfiddle.net/qWjnt/


text:
Q: Model data flow from (flow) port to UML activity diagram One of the projects I am working on uses flow ports to model data flow between classes. We now started to model dynamic behavior using activity diagrams and state charts and are looking for a way to express that the data used in an activity diagram has been received on a specific port. Bascially, we want to create a connector between a flow port and e.g. an activity parameter node.
I think modelling data flow with ports is quite common especially in System Engineering, and there should be ways to link the data to activities. I can think of two some ways:

*

*Connect the port to a property (or part) and use a ReadStructuralFeatureAction to get the value

*Connect the port to a property (or part) and add an operation to the class which is called with a CallOperation

*Create an attribute with the same name as the port and provide an operation that is called with a CallOperation action

The first option would be ok, but our modelling tool Rhapsody 8.1 seems to not support ReadStructuralFeatureActions. The other two approaches have the drawback that there is no direct connector between the port and the activity in the model and it is not visually obvious, so I would like to have a better alternative.
I am wondering if there anybody knows of better approaches to achieve this, e.g. using SysML (1.3).

A: The connections between the static and the dynamic views in UML and SysML are "hidden" in the less visible part of the model.  I guess the reason is that the designers of UML wanted to separate these. So there are no graphical or otherwise very explicit connections.
Instead, the connections are quite natural, so you can just use it. Examples are the guards, triggers or actions on transitions in state charts or activity diagrams. This ReadStructuralFeatureAction is implemented implicitely by using the static element directly. You can modell them directly there. So they occur next to the edge that represents the state transition or control flow. A futher way is to use Receive Actions and set the property of the reception to an event or an triggered Operation. By using Send Actions you can trigger Events in the same structural element or others. When doing so in Rhapsody you  need to specify the target Port and the target part.
Neither in UML/SysML or Rhapsody it is foreseen that you want to know via which port the call came or the attribute was changed, when you offer the interface of the Class/Block. But you can realize this by using full ports and implement the intended behaviour (which sould be distinctive - otherwise it would  not be needed to know the source). So each full port has a state chart or  activity and passes internal signals or events the object of your class. For calling operations from actions there are two ways, the more hidden one by just calling from the actions (or state on enter or leave) and the more visible one by using call operations.
The visibility of these connections have been changed in recent UML or SysML versions. So this will change significantly when updating to later Rhapsody versions; although I would really recommend to update to the latest Rhapsody version, as it brings better sysML support, far less bugs, a few new features and better usability.


text:
Q: Upgrading my ebike battery to give more speed and longer range I am in the early stages of trying to understand how to do this, so if you're kind enough to reply, please answer in simple terms if that's at all possible.
I want to add cells to my electric bike battery pack to increase the speed and the range. The speed is less important than the range - but a bit more would be nice. I've opened the case and found 5 banks of 8 x 18650 li-ion cells in there. I know that each bank is connected in series, with the cells in each bank connected in parallel. The bike is a Freego Hawk 36v. I have enough slots for another 20 cells (ie 2.5 banks). Would anyone know what is the best way to configure them to get much more range, and a bit of extra speed if possible. The existing cells are Samsung ICR 18650 26H li-ion, 2600mA, 3.65v.

A: To increase the speed you need to increase the voltage. To do this you need to be sure that both your motor and your controller are rated for this. It is very unlikely that your motor is rated for > 36 V so you will burn it out.

Figure 1. The Freego Hawk with rear-wheel hub motor.
If the motor is in the hub (which it is in the Hawk) then that leaves you with no ability to speed it up. My Kalkhoff / Panasonic drives the chain of the bike from a motor below the front chainwheel so I was able to reduce the rear sprocket from 21 to 19 teeth to gain more speed.
I can't comment on the batteries other than to say 0.5 of a battery bank isn't going to be any good. I imagine you're going to have trouble with charging.

A: Safest is probably to add an "auxilliary battery" completely separate from your existing one and switch to this as a reserve when needed.
As speed increases vehicle energy %age increasingly goes into combating "windage" as air drag increases with velocity cubed. If you can reduce effective frontal area and drag-coefficient you may achieve range improvements as good as is possible with the available extra cells.
Going slower also pays dividends when distance matters. A decrease in speed by 10% decreases drag energy needs by 100 x (1- 0.9^3) = 27% and probably increases range in average conditions by a similar amount at speeds above say 15 kph or so.
But first ...
The main issue with extending power packs of this sort is that, if you do not have a good understanding of what you are doing then there is a reasonable (or unreasonable) possibility that you will destroy some or all of the battery pack, the controller the bike miscellaneous bystanders and/or yourself.
Lithium ion cells have a charming mode known colloquially as "vent with flame".
This can be triggered by a range of unlikely events and if enough energy is available can resemble a slow hand grenade detonating. Even more and it may seem to resemble a moderately vast nad grenade, although actual explosion is generally absent. To get close to genuine explosion one may throw copious water on the comflagration which encourages the now gaseous lithium metal and perhaps released Hydrogen to perform a passable HG explosion.
In your case you have energy of roughly
Vcell x Ah-cell x cell-quantity Watt hours of energy or
Vcell x Ah-cell x seconds/hour x cell-quantity Joule.
Here = 3.6 x 2.6 x 40 =~ 375 Watt hours or
~= 1,350,000 Joule or Watt seconds
= 1,350 kilowatt seconds of energy.
or about 1800 horsepower seconds.
Spread this over say 10 seconds and assume only 50% gets made available and you have ~= 90 horsepower x 10 seconds of power delivery.
This would be not too foul if trying to make a mini electric dragster but not so good if its used to spread flaming chaos far and near.
So, you need to be careful.
You need to understand what you are doing.

That said,
Your present battery is described as an 8S5P arrangement (5 parallel strings of 8 batteries in series).
You should notionally be able to add additional strings of 8 cells in series.
in your case 2 strings x 8 cells  each, giving an 8S7P battery.
However:
Batteries added are presumably not the same age of history of the existing ones and may be different types. This can often lead to imbalance problems, early cell death, possibly early whole battery death and possibly slow handgrenades.
The 8S2P sub-battery could be used with a separate switch to provide a 'reserve tank'. The discharge rating of the cells may make this a bad idea. You should provide links to battery and bike data.
The existing 8S strings are hopefully provided with a means of balancing during charging. How any new strings can be added to the balancing system or if they can is TBD. Adding unbalanced strings is "unwise".
Your present battery capacity, assuming the same cells in current battery as you describe above is 2.6Ah x 5 strings = 13 Ah nominal. You could consider selling your existing cells and making a whole new battery. You can buy eg very long cycle life LiFePO4 batteries. These may come as separate cells or as 12V batteries. 3 x 12V x 20 Ah batteries would give about 40% more energy capacity than your existing cells. 3 x 40Ah x 12V = 3 x existing capacity. Weight is low compared to lead acid and slightly higher than LiIon per Wh.
As 'transistor' notes, speed PROBABLY comes from voltage - although it is possible that your system is speed limited below what it is capable of at the supplied voltage.
Note that liIon cells have Vout range of say 3V to 4.2V/cell so 8 in series gives 24V - 33.6 V. To get 36V with 8 cells you'd need V_cell = 36V/8 = 4.5V which is above what you can safely get from LiIon cells. ie the 36V is nominal. If the motor and controller can stand genuine 36V then you MAY be able to add one more cell per string.
9 x 4.2 = 37.8 V.
36/9 = 4V.
You'd REALLY need to check if say 38V for a while after charging was safe or might lead to slow hand grenading.
Charging a battery with 9 series cells is not hard but may annoy your existing charger.

A: The safest method is to buy a second battery pack or make one just like you already have. Switch and charge them as needed. Range is a big key so if it's a bicycle you can normally pedal to help assist the battery and double your range without much work.
Adding  more cells to the pack could be a problem with the motor voltage limit but most can handle more. It can also cause charging problems. So if you really want more range and speed you should buy a new high end model E bicycle. With lots of battery progress they cost less and go further.

A: I'm relatively new to electrical two-wheeled transportation and I'd like to share my experiences and get feedback on what I tried. I live in China, and as a foreigner, have not passed the driving test here. An electric scooter seems like the best and fastest way to get around with the least hassle as one does not need a license.
After 1-2 months of riding it around, it was great, but I also wanted more distance between charges, more speed, more power going uphill etc... I guess I'm being a little bit greedy, because it's already a pretty good bike. Everything being in Chinese, I am not 100% certain, but I believe my bike should have a 60V 20Ah sealed lead acid battery (SLA). The bike I have is more like a motor-cycle, it weighs 90kg, and doesn't have any pedals. It has a dashboard display that shows information like the speed, the distance travelled, the remaining charge (in bars) on the battery, indicating when you need to plug it in. It can go 25-30km before I lose the first bar (I was told it can go 70km between charges, by the salesperson, but have never tested it) with a top speed of about 40km/h, though the speedometer regularly shows over 50km/h when the battery is freshly charged. The fastest I'm able to clock on the speedometer is 56km/h on flat ground on power-level 3. But my GPS tells me I'm going just under 40km/h, and I trust the GPS more.
On the charger it is printed 60V 20Ah, and it looks like an oversized laptop charger. The way these kinds of bikes are charged in China is that you park next to a wall outlet, plug one side of the charger into the wall and the other end into your bike, the battery is not removable by the user. (upto) 8 hours later the charger cuts down to a trickle changing from red to green. The charger is big and clunky and looks rather cheaply built. The seat of my bike can be opened with some storage under it where the charger and lock and few other things can be kept.
After thinking about how to increase my range/speed/power, I decided to buy a Lithium ion battery online (JD.com). I got a 60V20Ah lithium battery for 1768 RMB (about US$270) https://item.jd.com/4523101.html and a Li-ion charger for 120 RMB https://item.jd.com/3138969.html. The Li-ion battery has the same kind of charging/discharging port that the bike has. My idea was to try to connect the Li-ion battery in parallel with the existing SLA battery. So I bought a cable that I thought would allow me to connect the batteries in parallel https://item.jd.com/13936790374.html. Unfortunately, this cable connects the batteries in series and I had to cut and reattach the cable to connect positive to postive and negative to negative. In addition, I bought a useful little voltmeter (https://item.jd.com/10663359922.html) that connects into the charging port on the bike which (I think) connects directly to the terminals of the SLA battery.
With the voltmeter, I could tell that after a full charge the SLA battery had a voltage of 68.5 V, while the Li-ion battery had a voltage of 71.4V. Based on this, I think that the Li-ion has 17 cells in series, with a nominal voltage of 3.7*17=62.9V. The difference between 68.5 and 71.4 seemed to be close enough that I could just plug the two batteries in parallel using my cut-and-reattached cable which I did. One point to be careful on, is that when reconnecting the cables, one must make very sure that they are connected in parallel and not anti-parallel which would short the positive to negative terminals of both batteries which would be really BAD. Use a multimeter to ensure the positive is connected to positive and negative to negative. Plugging one end of the cable into the Li-ion battery and the other end into the charging port of my bike completes the parallel circuit of the batteries.
So far, so good. The slightly higher voltage from the Li-ion battery pulls the voltage up when under load, and I'm now able to clock over 60km/h on the speedometer (in reality it's still in the 45km/h region). The motor and the controller of the bike seem to be able to take the extra amps/watts, nothing is burning or smoking. The battery just fits nicely under my seat and I can comfortably run my home-made cable from the Li-ion battery to the charging port on the bike to connect the two batteries in parallel.
I'd like to get the opinion of any battery experts out there, whether connecting batteries of different chemistries in parallel like this will cause any problems? I unplug and charge each battery separately with its own special charger designed for that chemistry. So far during the discharging (usage), I have yet to drop below 5 bars (which corresponds to 60V) on the dashboard before recharging, so I'm not pushing either battery near its limits. I don't think I'm doing any damage to either battery, but would like to know what others think.
In my mind, connecting the batteries in parallel means that for a given travel distance, the depth of discharge (DOD) is half of what it would be otherwise, meaning the strain on each battery is half. I expect that this will lengthen the life of both batteries.
If the above is correct, I think that connecting a second Li-ion battery in parallel with the in-built SLA battery is an ideal solution for my needs. It gives me the increased range, increased power (acceleration), increased top speed, reduced stress on the batteries reduced DoD and reduced charging time, since the batteries are discharged less between recharges.
Some points to note with a disclaimer: I am just sharing what I tried and seems to have worked pretty well so far for me. If you attempt this, but don't know what you're doing, you could cause some serious damage, so do so at your own risk. Things that come to my mind in particular that you want to watch out for: Make absolutely sure the positive terminal of one battery is connected to the positive terminal of the other battery and same for the negative. Getting this wrong could be quite devastating. At the very least, sparks and a burnt out cable, with worse case scenarios including, fire, venting and possible explosion (I'm thinking of the Li-ion battery in particular). I would also recommend charging each battery separately with the chargers designed for those batteries rather than charging the batteries together with one charger. When you reconnect the batteries in parallel, some current will flow from the higher voltage battery to the lower voltage battery, equalizing the voltages somewhere in between. So one should ensure this voltage difference between the two batteries is not too large before reconnecting them, to avoid large currents flowing between the batteries (eg: do not connect at 60V and a 48V battery in parallel). I believe this should not be a problem for the batteries if this is observed. Perhaps others have some advice to share on this.


text:
Q: How to this without repeating code? Xamarin - Android i don't want to repeat this code all times:
Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);

How i can improve this code to look more clean?
This spam of code can really affect the performance of the application?
 protected override void OnResume()
    {
        base.OnResume();
        Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
        Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);

        btnWarning.Click += btnWarn;
    }

    protected override void OnPause()
    {
        base.OnPause();
        Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
        Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);

        btnWarning.Click -= btnWarn;

    }

    private void btnWarn(object sender, EventArgs e)
    {
        Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
        btnWarning.Text = string.Format("Warning Test");
    }

A: Make the buttons class variables and then in OnCreate:
Button btnClicks;
Button btnWarning;

protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);
   btnClicks = FindViewById<Button>(Resource.Id.MyButton);
   btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
   btnWarning.Click += btnWarn;
}

now,
private void btnWarn(object sender, EventArgs e)
{
   btnWarning.Text = string.Format("Warning Test");
}

A: Do you really need to remove the Click handler on pause?
It is usually enough to initialize the handler in OnCreate and that's it.
If you do need to access views more than once, then keep a reference to the view in the Activity class itself:

class MyActivity : Activity
{
  Button myButton;

  protected override void OnCreate(Bundle bundle)
  {
     base.OnCreate(bundle);
     var myButton = FindViewById<Button>(Resource.Id.MyButton);
  }

  protected override void OnPause()
  {
    // do something with myButton
  }
}

A: Whenever you subscribe to an event, you should unsubscribe as well to release any memory resources attached to the activity. If you don´t unsubscribe, you may get OutOfMemoryException eventually. Actually, you were doing that part correctly, but as others mentioned, you need to use OnCreate to find views just once:
Button btnClicks;
Button btnWarning;

protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);

   btnClicks = FindViewById<Button>(Resource.Id.MyButton);
   btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
}

protected override void OnResume()
{
    base.OnResume();

    btnWarning.Click += btnWarn;
}

protected override void OnPause()
{
    base.OnPause();

    btnWarning.Click -= btnWarn;
}


text:
Q: aws session manager to instances without public IP or EIP I am trying to set up session manager to connect to my instances, and I am facing an issue with instances that do not have public IP or EIP.
What I have done is created a role and attach the  AmazonSSMManagedInstanceCore Policy.
When I launch an instance (Amazon 2 or Ubuntu) with public IP or EIP everything is ok, as soon as I attach the role it works.
But when I do not have Public IP or EIP I am not able to connect.
Any idea? Am I missing something?

A: The instances must be able to connect to SSM service endpoint. If they don't have a Public IP then they must be in a subnet with  default route through a NAT gateway. Otherwise they can't talk to the internet and in turn can't connect to the SSM service
See NAT Gateway for EC2 instances for more details.
Hope that helps :)

A: Thanks, yes indeed it helps.
I was using public subnet with IGW, shouldn't that work as well since my instances they do have internet access , but via the IGW instead.


text:
Q: Create model instance consisting of many-to-many field I am trying to create a model instance using a post request, however one issue that I am having is that the model consists of a field which is of many-to-many. Now I am at a stage where I have got an array consisting of primary keys of the model instances (Modules) I wish to associate with the model I am trying to create (a Student).
Please see my code below as I do not know where I am going wrong, after some basic research it seems I need to use a .set() method.
The PUT['modules']  corresponds to array that consists of values [1,2,3,5].
def create_student(request):
    """API for creating a student"""
    if request.method == "POST":
        PUT = json.loads(request.body)
        student = Student(name=PUT['name'], join_date=PUT['join_date'], academic_year=PUT['academic_year'],
                          modules=PUT['modules'] # THIS IS WHERE I NEED HELP
                          )
        student.save()
        return JsonResponse(student.to_dict())

    return HttpResponseBadRequest("Invalid method")

Thank you for your time.

A: In order to populate a ManyToManyField relation, first the two items that you want to link need to be saved. This is necessary since otherwise these do not have a primary key: one links two items by adding a record in the junction table with the two primary keys to link.
If you thus want to link the Student you are constructing with the modules, you first create the student, and then you can use student.modules.add(…) to link it to the (existing) modules by unpacking a list of the primary keys of the modules:
def create_student(request):
    """API for creating a student"""
    if request.method == "POST":
        PUT = json.loads(request.body)
        student = Student.objects.create(
            name=PUT['name'], join_date=PUT['join_date'], academic_year=PUT['academic_year']
        )
        student.modules.add(*PUT['modules'])
        return JsonResponse(student.to_dict())
    else:
        # …


text:
Q: setting LD path for submitting job via qsub to a remote cluster Python I am trying to use tensorflow on a cluster with outdated GLIC library.
I have tried following the steps explained in this page: Error while importing Tensorflow in python2.7 in Ubuntu 12.04. 'GLIBC_2.17 not found'
It works when I run it with a normal python command (which python = /anaconda2/bin/python)
I need to run my program using the qsub command (script submission) in the cluster but I get the following error:
    Traceback (most recent call last):
  File "/users/k15/helloada.py", line 2, in <module>
    import tensorflow as tf
  File "/users/k15/anaconda2/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in <module>
    from tensorflow.python import *
  File "/users/k15/anaconda2/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 48, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/users/k15/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/users/k15/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: /lib64/libc.so.6: version `GLIBC_2.17' not found (required by /users/k15/anaconda2/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so)

The problem is that I cannot use the following line:
LD_LIBRARY_PATH="$HOME/my_libc_env/lib/x86_64-linux-gnu/:$HOME/my_libc_env/usr/lib64/" $HOME/my_libc_env/lib/x86_64-linux-gnu/ld-2.17.so `which python`

with the qsub command. (I can make tensorflow work normally by running python with the above line.)
The qsub uses a script file with the following structure:
#!/bin/sh
INPUT=/users/k15/file.py

EXEC=home/k15/anaconda2/bin/python

$EXEC $INPUT

I am at a loss on how to make this work, any help would be greatly appreciated.


text:
Q: URL Scheme not opening view I'm trying to implement a custom URL Scheme where one particular URL (myapp://article) opens the article view. I'm not having any success though.
Normally the app opens the LoginViewController as is defined in the Storyboard. For the URL Scheme I'm doing this:
-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation{

    if ([[PocketAPI sharedAPI] handleOpenURL:url]) {
        NSLog(@"Login complete!");
        return YES;
    } else {
        NSLog(@"url recieved: %@", url);
        NSLog(@"scheme: %@", [url scheme]);
        NSLog(@"query string: %@", [url query]);
        NSLog(@"host: %@", [url host]);

        if ([[url host] isEqualToString: @"article"]) {
            Stream *stream = [[Stream alloc] initWithDictionary:data];

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

            ArticleViewController *articleViewController = [storyboard instantiateViewControllerWithIdentifier:@"ArticleViewController"];

            articleViewController.stream = stream;

            [self.window makeKeyAndVisible];
            [self.window.rootViewController presentViewController:articleViewController animated:YES completion:NULL];
            return YES;
        }
        return YES;
    }
}

I keep getting Warning: Attempt to present <ArticleViewController: 0x79040cb0> on <LoginViewController: 0x7906f8c0> whose view is not in the window hierarchy!
What am I doing wrong?

A: Try showing the window first before instantiating your view controller. Before you instantiate the window the main view controller is indeed not in the view hierarchy (because there is none yet).


text:
Q: How to set null to a variable in freemarker I can't find anything related to this on any question, and it is something really basic, but I can't figure it out.
So my problem is that I don't know how to set null to a variable in freemarker.
Example:
${hi!"bye"}          <#-- Prints "bye" because hi is undefined -->
<#assign hi="hi">    <#-- Sets a value to the var hi -->
${hi!"bye"}          <#-- Prints "hi" because hi has a value -->
<#assign hi=null>    <#-- This does not work but is what I am looking for -->
${hi!"bye"}          <#-- I want it to print "bye" because hi should be undefined -->

I have this problem because I iterate over a list and set a var if some logic to the specific item validates, and then check if the var exists, but if the first item creates the var, then I will have the var set for the rest of the items in the list.

A: You could assign an empty string to your variable and check with the buit-in ?has_content if it is set:
${hi?has_content?then(hi, "bye")}
<#assign hi="hi">
${hi?has_content?then(hi, "bye")}
<#assign hi="">
${hi?has_content?then(hi, "bye")}

This will render:
bye
hi
bye

A: Depending on what you need it for, you can use a different type to indicate a "missing" value.
For instance, if you have myVariable that is normally a number, assign  false to it, and then instead of checking myVariable??, check myVariable!false?is_number. This will cover both cases (non-existent and "unset").
${ (myVariable!false?is_number)?c }

<#assign myVariable = 12 >
${ (myVariable!false?is_number)?c }

<#assign myVariable = false >
${ (myVariable!false?is_number)?c }

Result:
false
12
false

Go try.

A: No, there's no "unassign", nor the concept of null exists in FreeMarker (until 2.4.0 at least, but that's far away anyway). It only have missing variables (maybe technically a null, maybe doesn't exist at all) and those that are there. I don't really get why is that needed in your case. Can you show a simplified example of the situation?


text:
Q: MVC ~/ not resolving to application root in virtual directory I have multiple websites hosted on the same server with structure as follows:
http://primary-domain.com/hostedsites/MVCWebApplication1/ = http://MVCWebApplication1.com/
http://primary-domain.com/hostedsites/MVCWebApplication2/ = http://MVCWebApplication2.com/
...
The problem is, all ~/ references made in a hosted site (i.e. MVCWebApplication1, MVCWebApplication2, etc) resolve to
http://MVCWebApplication1.com/hostedsites/MVCWebApplication1/
and not
http://MVCWebApplication1.com
Please note:
I already have the following my web.config:
<rule name="Remove Virtual Directory">
  <match url=".*" />
  <action type="Rewrite" url="{R:0}" />
</rule>

How can I fix this?

A: What I ended up doing was using a bunch of work arounds:
In web.config:
<rewrite>
  <rules>
    <rule name="Remove Virtual Directory">
      <match url=".*" />
      <action type="Rewrite" url="{R:0}" />
    </rule>
  </rules>
</rewrite>

And instead of creating links like this:
Help

doing this:
@Html.ActionLink("Help", "Help") // This seems to create clean urls

A: You just need to convert your virtual directories to applications in IIS.